Search code examples
cmultidimensional-arrayappendc-stringsstrcpy

Adding/appending string into an array of strings


Let's say I have an array that looks like:

char arr[MAX_ARR_LENGTH][30] = {"Tom", "and", "Jerry" };

Now, how do I append a new string that the end of the array? Let's say I want to add "Jack" as a new element so the array shoud look like:

char arr[MAX_ARR_LENGTH][30] = {"Tom", "and", "Jerry", "Jack" };

How do you achieve this in C?

I tried using for loops but because it is a 2D array, I wasn't able to figure out the right technique.


Solution

  • The other answers are good and correct, but to be as simple as possible:

    #define MAX_ARR_LENGTH 10
    #define MAX_STR_LENGTH 30
    
    char * arr[MAX_ARR_LENGTH][MAX_STR_LENGTH];
    size_t arr_size = 0;  // number of elements in use
    

    To add an element:

    if (arr_size < MAX_ARR_LENGTH)
      strcpy(arr[arr_size++], "Jill");