Possible Duplicate:
C - Difference between “char var[]” and “char *var”?
Difference between char a[]=“string”; char *p=“string”;
would someone explain what exactly the difference between char[] and char* is? for example difference between
char name[] = "earth";
and
char *name = "earth";
thanks
char namea[] = "earth";
char *pname = "earth";
One is an array (the name namea
refers to a block of characters).
The other is a pointer to a single character (the name pname
refers to a pointer, which just happens to point to the first character of a block of characters).
Although the former will often decay into the latter, that's not always the case. Try doing a sizeof
on them both to see what I mean.
The size of the array is, well, the size of the array (six characters, including the terminal null).
The size of the pointer is dependent on your pointer width (4 or 8, or whatever). The size of what pname
points to is not the array, but the first character. It will therefore be 1.
You can also move pointers with things like pname++
(unless they're declared constant, with something like char *const pname = ...;
of course). You can't move an array name to point to it's second character (namea++;
).
(1) char name[] = "earth";
name
is an character array having the contents as, 'e'
,'a'
,'r'
,'t'
,'h'
,0
. The storage location of this characters depends on where name[]
is declared (typically either stack or data segment).
(2) char *name = "earth";
name
is a pointer to a const string. The storage location of "earth"
is in read-only memory area.
In C++, this is deprecated and it should be const char *name = "earth";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With