char c[] = \"Hello\";
char *p = \"Hello\";
printf(\"%i\", sizeof(c)); \\\\Prints 6
printf(\"%i\", sizeof(p)); \\\\Prints 4
My question is:
Why
It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char *
and char []
) are not the same thing.
char a[SIZE]
says that the value at the location of a
is an array of length SIZE
char *a;
says that the value at the location of a
is a pointer to a char
. This can be combined with pointer arithmetic to behave like an array (eg, a[10]
is 10 entries past wherever a
points)In memory, it looks like this (example taken from 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 to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.
One major practical difference is that the compiler knows how long an array is. Using the examples above:
char a[] = "hello";
char *p = "world";
sizeof(a); // 6 - one byte for each character in the string,
// one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
// probably 4 or 8 on most machines (depending on whether it's a
// 32 or 64 bit machine)