Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between char[] and char*? [duplicate]

Tags:

c++

c

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

like image 260
user1012169 Avatar asked Oct 16 '25 04:10

user1012169


2 Answers

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++;).

like image 115
paxdiablo Avatar answered Oct 17 '25 18:10

paxdiablo


(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";

like image 23
iammilind Avatar answered Oct 17 '25 18:10

iammilind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!