0

I'm currently learning C and am having a bit of trouble understanding how to declare a string. I understand that in C, strings are simply arrays of characters. I've seen two different ways for declaring a string:

char[] some_string = "hello world";

and

char *some_string = "hello world";

When should each of these be used? Most code I've seen uses the char *some_string syntax, but I'm sure that there's a reason why. Thanks.

Ryan
  • 7,621
  • 5
  • 18
  • 31
  • I believe that this is pretty much the same thing. char[] is (internally) treated as char*. *(char + i) == char[i] == *(i + char) == i[char] – Beko Feb 08 '15 at 01:47
  • 2
    @Beko: that's really not true; arrays are not simply pointers. Your identity is more or less valid; you can't use `char` as a variable name, of course. But given `int i = 2; char *ptr = "str";` then `*(ptr + i)` ≡ `ptr[i]` ≡ `*(i + ptr)` ≡ `i[ptr]`. Given `char array[20];`, places where arrays differ from pointers include the type of `&ptr` (which is `char **`) vs type of `&array` (which is `char (*)[20]` — pointer to array of `char` of size 20), and `sizeof(ptr)` (typically 4 on a 32-bit system, 8 on a 64-bit system) vs `sizeof(array)` (which is 20 on all systems). – Jonathan Leffler Feb 08 '15 at 02:14

1 Answers1

1

char some_string[] = "foo" declares a local array of size 4 which is initialized at run time with the values 'f', 'o', 'o', and '\0'. That memory is (probably) on the stack of the function. char *some_string = "foo" declares a pointer which is initialized to the location of a string which is initialized at compile time to the same values. The string char [] some_string = "foo" is a syntax error. The most relevant difference between the two is that, on many platforms, the latter is not writable. In other words, some_string[1] = 'a' will generate a segfault on some platforms if some_string was declared as a pointer rather than an array.

William Pursell
  • 204,365
  • 48
  • 270
  • 300