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"};
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"};
No. Actually it's the "same" as
Every character is a separate element, with an additional
\0
character as a string terminator.I quoted "same", because there are some differences between
char * array
andchar array[]
. If you want to read more, take a look at C: differences between char pointer and arrayNo, you're creating an array, but there's a big difference:
The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:
creates the same, read only, constant string, and copies it to the stack array. That's why:
Is valid in the latter case.
If you write:
the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:
Where the last version gives you an array of strings (arrays of chars) that you actually can edit...
It's very similar to
but gives you read-only memory.
For a discussion of the difference between a
char[]
and achar *
, see comp.lang.c FAQ 1.32.The declaration and initialization
declares a pointer
array
and make it point to a constant array of 31 characters.The declaration and initialization
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:
And like this for the second:
Arrays decays to pointers to the first element of an array. If you have an array like
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 fromarray
(or its equivalent&array[0]
). While both&array
and&array[0]
point to the same location, the types are different. Using the arrat above,&array
is of typechar (*)[31]
, while&array[0]
is of typechar *
.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:
With the above, you can access the fourth element (the
'b
' character) using eitheror
And because addition is commutative, the last can also be expressed as
which leads to the fun syntax