char *array and char array[]

arrays, c, char, pointers

Solution

The declaration and initialization

char *array = "One good thing about music";

declares a pointer `array` and make it point to a (read-only) array of 27 characters, including the terminating null-character.

The declaration and initialization

char array[] = "One, good, thing, about, music";

declares an array of characters, containing 31 characters.

And yes, the size of the arrays is 31, as it includes the terminating `'\0'` character.

Laid out in memory, it will be something like this for the first:

+-------+     +------------------------------+
| array | --> | "One good thing about music" |
+-------+     +------------------------------+

And like this for the second:

+------------------------------+
| "One good thing about music" |
+------------------------------+

Arrays decays to pointers to the first element of an array. If you have an array like

char array[] = "One, good, thing, about, music";

then using plain `array` when a pointer is expected, it's the same as `&array[0]`.

That mean that when you, for example, pass an array as an argument to a function it will be passed as a pointer.

Pointers and arrays are almost interchangeable. You can not, for example, use `sizeof(pointer)` because that returns the size of the actual pointer and not what it points to. Also when you do e.g. `&pointer` you get the address of the pointer, but `&array` returns a pointer to the array. It should be noted that `&array` is very different from `array` (or its equivalent `&array[0]`). While both `&array` and `&array[0]` point to the same location, the types are different. Using the array above, `&array` is of type `char (*)[31]`, while `&array[0]` is of type `char *`.

For more fun: As many knows, it's possible to use array indexing when accessing a pointer. But because arrays decays to pointers it's possible to use some pointer arithmetic with arrays.

For example:

char array[] = "Foobar";  /* Declare an array of 7 characters */

With the above, you can access the fourth element (the `'b`' character) using either

array[3]

or

*(array + 3)

And because addition is commutative, the last can also be expressed as

*(3 + array)

which leads to the fun syntax

3[array]

Problem

if I write this ``` char *array = "One good thing about music"; ``` I actually create an array? I mean it's the same like this? ``` char array[] = {"One", "good", "thing", "about", "music"}; ```

Original source

Related problems