How would I make a array of strings in C?

I’m attempting to make a array of strings in C. If I use this code:

char (*a[2])[14];
a[0]="blah";
a[1]="hmm";

gcc gives me “warning: assignment from incompatible pointer type”. What is the right method for doing this?

char (*a[2])[14]

is, I think, an array of 14 items, each of which is an array of two char*, so a total of 28 pointers and no characters. Or it might be 14 strings each of which is two characters long; not sure which. I looked at it in the debugger & it’s kind of a mess.

If you want an array of two strings each of which can be no more than 13 characters plus a null terminator, then you want simply

char a[2][14];

You’d then have to use strncpy to fill the arrays:

strncpy(a[0], "blah", 14);
strncpy(a[1], "hmm", 14);

Alternatively, you could have a be an array of two character pointers which could point to strings of any length:

char *a[2];
a[0] = "blah";
a[1] = "hmm";

Arrays of things in C, the Ferrari of Programming Languages :slight_smile:

Types of arrays

Given a value of type T:

// Type of a 1D array of values of type T
T []

// Typical use case
void foo (T [5])
       // number of elements is 5
void foo (T [ ], int M) 
      // M denotes the number of elements

// Type of a 2D array of values of type T
T [][M]

// Typical use case
void foo (T [7][16])
       // 7 rows and 16 columns
       // 7 x 16 elements
void foo (T [ ][16], int M)
       // M denotes the number of rows
       // 16 columns
       // M x 16 elements

For example, type for an array of strings:

Given a value of type T = char *:

// Type for a 1D array of strings
char * []

// Typical use case
void foo (char * [5])
       // number of elements is 5
void foo (char * [ ], int M) 
      // M denotes the number of elements

// Prototypical use case
int main (int argc, const char  * argv [])

Finally, C does not provide support for array sizes. The end or size of an array has to be specified somehow. For example, a string literal is an array of characters; its end is specified by the compiler inserting an extra null character immediately after the last character in the string.

For example:

const char * odo = "Odo"
// 'odo' points to the first character of the string literal

To create the string literal "Odo", the compiler creates an array of characters 
and terminates the array by inserting the null character '\0' at the end: 
 {'O', 'd', 'o', '\0'}