Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string array declaration in c [closed]

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?

like image 210
Rakesh Babu Avatar asked Oct 23 '13 12:10

Rakesh Babu


People also ask

Can I declare a string array in C?

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.

How do I initialize a string array in C?

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' };

How is C string terminated?

All strings in c are terminated with byte 0.


2 Answers

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"};
like image 198
interjay Avatar answered Sep 19 '22 23:09

interjay


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

like image 42
P.P Avatar answered Sep 20 '22 23:09

P.P