...Regardless of the answer to that question..
Why isn't there 2 of [] ?
Semantics may be affecting your understanding of arrays and their indexing requirements. C
has arrays for int
and char
, each requiring a single set of []
to define. There is a special kind of char
array in C
commonly referred to as a C String
, which is just a regular char
array with the last character being the null terminator: \0
. An array of C strings
does commonly use two sets of brackets: [][]
.
The rules for representing a char
array are the same as those for representing an int
array. both can be described as a collection of values stored in a contiguous set of memory locations. To illustrate, example arrays of int
, char
and a C string
follow:
int numarr[] = {99,104,97,114,32,97,114,114,97,121,0};
char chararr1[] = {'c','h','a','r',' ','a','r','r','a','y','\0'};
char chararr2[] = {99,104,97,114,32,97,114,114,97,121,0};
char string[] = {"char array"};
The array values in each of the 4 examples above are identical. In most implementations, the int
array is stored in a contiguous set 4 byte memory locations, while each of the char
arrays are stored in a contiguous set of 1 byte memory locations. The three char
arrays, if used in printf()
would result in the same string output, as each is an array of char
terminated with a null value.
printf("%s\n%s\n%s\n", chararr1, chararr2, string);
char array
char array
char array
More about the special char
array - C string, and arrays of C string
char string[] = {"this is a string"};
A C string is defined an a null terminated array of char
: The content de-marked between ^
is string
defined above. Note the null termination.
|t|h|i|s| |i|s| |a| |s|t|r|i|n|g|\0|?|?|
^ ^
A contiguous set of C strings, or array of C strings however can be represented by using two set of square brackets:
char strings[2][20] = {"first string", "second string"};
This array of string would look like this in memory:
|f|i|r|s|t| |s|t|r|i|n|g|\0|s|e|c|o|n|d| |s|t|r|i|n|g|\0|?|?|?|
| | | |
[0] | | [1] 1st index used to access full string
[0][4]='t' [0][10]='n' 2nd index used to access array elements
While each string can be accessed by using the first index,
eg. strings[0] = "first string" and strings[1] = "second string"
each character of each string can be accessed using the first and second index
eg. strings[0][0] == 'f' and strings[1][0] == 's'