How do I create an array of strings in C?

Charles picture Charles · Jul 6, 2009 · Viewed 1M times · Source

I am trying to create an 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 correct way to do this?

edit: I am curious why this should give a compiler warning since if I do printf(a[1]);, it correctly prints "hmm".

Answer

Mikael Auno picture Mikael Auno · Jul 6, 2009

If you don't want to change the strings, then you could simply do

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

When you do it like this you will allocate an array of two pointers to const char. These pointers will then be set to the addresses of the static strings "blah" and "hmm".

If you do want to be able to change the actual string content, the you have to do something like

char a[2][14];
strcpy(a[0], "blah");
strcpy(a[1], "hmm");

This will allocate two consecutive arrays of 14 chars each, after which the content of the static strings will be copied into them.