Difference between these declarations ?
1.
char **strings = {"abc", "bca", "rat", "tar", "far"};
2.
char *strings[] = {"abc", "bca", "rat", "tar", "far"};
3.
char strings[][] = {"abc", "bca", "rat", "tar", "far"};
Only (2) is a valid declaration. What is the difference between these types and why are (1) and (3) not valid?
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.
A more convenient way to initialize a C string is to initialize it through character array: char char_array[] = "Look Here"; This is same as initializing it as follows: char char_array[] = { 'L', 'o', 'o', 'k', ' ', 'H', 'e', 'r', 'e', '\0' };
All strings in c are terminated with byte 0.
char **strings
Is a pointer to a pointer to char
. It's a valid type, but you can't initialize it with an array initializer as you're trying to do.
char *strings[]
is an array of pointers to char
, and your initialization of it is valid.
char strings[][]
is an attempt to make a two-dimensional array, but it's wrong because you have to specify the size of all dimensions except the outermost one (the outermost size can be deduced from the initializer). So this would be valid:
char strings[][4] = {"abc", "bca", "rat", "tar", "far"};
C99 supports compound literals and thus you can assign an array initializer. So case 1 is also fine with:
char **strings = (char *[]) {"abc", "bca", "rat", "tar", "far"};
C99 draft, 6.5.2.5, Compound literals
Constraints
1 The type name shall specify an object type or an array of unknown size, but not a variable length array type.
2 No initializer shall attempt to provide a value for an object not contained within the entire unnamed object specified by the compound literal.
3 If the compound literal occurs outside the body of a function, the initializer list shall consist of constant expressions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With