c - Sizes of arrays declared with pointers -


char c[] = "hello"; char *p = "hello";  printf("%i", sizeof(c)); \\prints 6 printf("%i", sizeof(p)); \\prints 4 

my question is:

why these print different results? doesn't c[] declare pointer points first character of array (and therefore should have size 4, since it's pointer)?

it sounds you're confused between pointers , arrays. pointers , arrays (in case char * , char []) not same thing.

  • an array char a[size] says value @ location of a array of length size
  • a pointer char *a; says value @ location of a pointer char. can combined pointer arithmetic behave array (eg, a[10] 10 entries past wherever a points)

in memory, looks (example taken the faq):

 char a[] = "hello";  // array     +---+---+---+---+---+---+ a: | h | e | l | l | o |\0 |    +---+---+---+---+---+---+   char *p = "world"; // pointer     +-----+     +---+---+---+---+---+---+ p: |  *======> | w | o | r | l | d |\0 |    +-----+     +---+---+---+---+---+---+ 

it's easy confused difference between pointers , arrays, because in many cases, array reference "decays" pointer it's first element. means in many cases (such when passed function call) arrays become pointers. if you'd know more, this section of c faq describes differences in detail.

one major practical difference compiler knows how long array is. using examples above:

char a[] = "hello";   char *p =  "world";    sizeof(a); // 6 - 1 byte each character in string,            // 1 '\0' terminator sizeof(p); // whatever size of pointer            // 4 or 8 on machines (depending on whether it's             // 32 or 64 bit machine) 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -