Search code examples
carraysmultidimensional-arraycstring

Arrays of strings in C


I need to hold an array of C strings. Now I know C strings are just an array of chars so essentially what I want is a 2d array of chars. The strings I'm trying to store will also never exceed 6 characters. My plan is to initialize a char array with 50 "string slots" and then if I hit 50 strings reallocate the array's memory to double it's capacity. I've tried something simple like:

int main() {
    char strings[50][6];
    strings[0] = "test";
    printf("The string is: %s", strings[0]);
    return(0);
}

But, when I go to compile it I get the following error:

test.c: In function ‘main’: test.c:3: error: incompatible types when assigning to type ‘char[6]’ from type ‘char *’ test.c:4: warning: incompatible implicit declaration of built-in function ‘printf’

Can anyone point in me in the right direction?


Solution

  • strncpy(strings[0], "test", 6); unless your C library has strlcpy(). However if you are going to need to vary the size of the storage, you're better off using a char ** with malloc(), realloc() and free().