3

In my GCC 32-bit compiler, the following code gives the output

char *str1="United";
printf("%s",str1);

output:

United

then should I consider char *str1="United"; the same as char str1[]="United"?

Kevin
  • 53,822
  • 15
  • 101
  • 132

3 Answers3

2

The two are not the same: char *str1="United" gives you a pointer to a literal string, which must not be modified (else it's undefined behavior). The type of a literal string should really be const but it's non-const for historical reasons. On the other hand, char str1[]="United" gives you a modifiable local string.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • "The type of a literal string should really be const char*" - what is the type of a string literal in C? – Luchian Grigore Jun 09 '13 at 03:46
  • @LuchianGrigore technically a string literal is an anonymous `char[]`, which can only be pointed to (via `char *`). The `const`s are not part of the string literal's type, though (as stated) they incur UB if one attempts to change them. – Kevin Jun 09 '13 at 03:54
1

char* str = "United"; is read-only. You wouldn't be able to reach inside the string and change parts of it:

*str = 'A';

Will most likely give you a segmentation fault.

On the other hand char str1[] = "United"; is an array and so it can be modified as long as you don't exceed the space allocated for it (arrays cannot be resized). For example this is perfectly legal:

char str[] = "United";
str[0] = 'A';
printf("%s\n", str);

This will print Anited.

Nobilis
  • 7,310
  • 1
  • 33
  • 67
  • In `char *str = "United";`, the initialization copies a pointer value into the pointer object `str`. In `char str[] = "United";`, the initialization copies the 7-byte array value (`"United"` plus the terminating `'\0'`) into the *array* object `str`. – Keith Thompson Jun 09 '13 at 06:20
  • Yes, `char str[] = "United";` is equivalent to `char str[] = {'U', 'n', 'i', 't', 'e', 'd', '\0'};`. There is an implicit '\0' at the end. A proof of this is that `sizeof(str)` yields 7. – Nobilis Jun 09 '13 at 06:36
1

See the comp.lang.c.faq, question 1.32. It basically boils down to the fact that declaring the string in array form (char str[] = "foo") is identical to char str[] = {'f','o','o'}, which is identical to char str[] = {102, 111, 111}; that is, it is a normal array on the stack. But when you use a string literal in any other context it becomes "an unnamed, static array of characters, [which] may be stored in read-only memory, and which therefore cannot necessarily be modified." (And trying to modify it results in undefined behavior wherever it happens to be stored, so don't).

Kevin
  • 53,822
  • 15
  • 101
  • 132