Take the 2-minute tour ×

Possible Duplicate:

In C code, When we declare a string, what happens differently in these two cases?

char * p = "Hello World";


char p[] = "Hello World";

I realize that in the first case the string literal is constant and cannot be modified while in the second case the string pointed to by p can be modified, but please tell me what actually happens in the background.

Please answer in terms of how and where memory is allocated, what point to where and if any new memory is given. Also, if there is any difference in c and c++ in this regard.

share|improve this question
I don't think the standards mention memory. Instead they talk about storage duration (§ 6.2.4, ISO/IEC 9899). –  Micha Wiedenmann Nov 25 '12 at 12:43
Neither is a "string", since there are no "strings" in C (although there are "string literals"). The first is a pointer to the first byte in a sequence of bytes, the second is an array of bytes. –  Kerrek SB Nov 25 '12 at 12:44
add comment

marked as duplicate by Alok Save, Blue Moon, simonc, FredOverflow, pmr Nov 25 '12 at 12:48


3 Answers

up vote 6 down vote accepted

const char * is a pointer to a char. "Hello World" could be created in a read memory section, so you can't/shouldn't modify it...

char[] is a mutable array of characters. The array would be created on the stack.

share|improve this answer
You meant const char * –  Maciej Ziarko Nov 25 '12 at 12:40
Yeah, thanks Maciej –  Lews Therin Nov 25 '12 at 12:40
Don't you mean it could be created in a read only section? Since there are no guarantees whatsoever about that. –  Grizzly Nov 25 '12 at 12:41
When you say char[] is created on the stack, is the memory assigned at run time or compile time? –  Xero Nov 25 '12 at 12:45
@Xero I would say it depends on the implementation, and if the compiler chooses to optimize it. –  Lews Therin Nov 25 '12 at 12:46
show 1 more comment

Pointers (ie. the '*') should be used where the passing "NULL" is meaningful. whereas [] is used for arrays

share|improve this answer
There are other reasons to use pointers besides the ability to pass NULL, particulary in C. –  Grizzly Nov 25 '12 at 12:43
That was one point which came to my mind when I took that question. I definitely agree that there are other reasons too. –  Rahul Tripathi Nov 25 '12 at 12:44
add comment

The result is the same, but the declaration is different, when you say char* a[] you declare a pointer to the first position of the string, but it can be modified, if you say const chat * a it can't because the prefix const doesn't allow you. In the other hand you have char a[] which declares an array filled with characters and It can be modified at anytime, and its starting size will be related to the length of your string.

share|improve this answer
Probably char* a[] should be char* a. –  effeffe Nov 25 '12 at 13:16
add comment
