Home > Net >  Adding/appending string into an array of strings
Adding/appending string into an array of strings

Time:01-19

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.

CodePudding user response:

To copy data into your existing array if there is sufficient space (MAX_ARR_LENGTH > 3):

strcpy(arr[3], "Jack");

If you are copying a variable check it's size is < 30 with strlen() first.

You cannot expand an automatic array. Instead you want to allocate it using dynamic memory:

// alternatively use calloc() or malloc()
char **arr = realloc(NULL, 30 * MAX_ARR_LENGTH);
if(!arr) {
  // handle error
}

char **tmp = realloc(arr, 31 * MAX_ARR_LENGTH);
if(!tmp) {
  // handle error
}
arr = tmp;

You can also use use an array syntax for allocation:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    char (*arr)[30] = malloc(sizeof(char[3][30]));
    strcpy(arr[0], "Tom");
    strcpy(arr[1], "and");
    strcpy(arr[2], "Jerry");
    char (*tmp)[30] = realloc(arr, sizeof(char[4][30]));
    if(!tmp) {
        // handle error
    }
    arr = tmp;
    strcpy(arr[3], "Jack");
}

CodePudding user response:

In this declaration

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

you declared an array of MAX_ARR_LENGTH elements of the type char[30] and initialized it with three string literals.

I suppose that the value of MAX_ARR_LENGTH is greater than 3.

In this case all other elements of the array that were not explicitly initialized by the string literals are implicitly initialized by zero. It means that all other elements are initialized as empty strings.

So to append a new string to the array you can write for example

#include <string.h>

//...

size_t i = 0;

while ( i < MAX_ARR_LENGTH && arr[i][0] != '\0' )   i;

if ( i < MAX_ARR_LENGTH ) strcpy( arr[i], "Jack" );

Here is a demonstration program.

#include <stdio.h>
#include <string.h>

#define MAX_ARR_LENGTH 10

int main( void )
{
    char arr[MAX_ARR_LENGTH][30] = { "Tom", "and", "Jerry" };

    for (size_t i = 0; i < MAX_ARR_LENGTH && arr[i][0] != '\0'; i  )
    {
        printf( "%s ", arr[i] );
    }
    putchar( '\n' );

    size_t i = 0;

    while (i < MAX_ARR_LENGTH && arr[i][0] != '\0')   i;

    if (i < MAX_ARR_LENGTH) strcpy( arr[i], "Jack" );

    for (size_t i = 0; i < MAX_ARR_LENGTH && arr[i][0] != '\0'; i  )
    {
        printf( "%s ", arr[i] );
    }
    putchar( '\n' );
}

The program output is

Tom and Jerry
Tom and Jerry Jack
  • Related