Search code examples
cmultidimensional-arraydynamic-memory-allocationc-stringsrealloc

C Increase char array of char array size


I have a char array of char array like so:

char my_test[2][10];

As you can see I have a length of 2 and then 10. If I need to increase the first char array (2), how can this be done dynamically?

For example, half way through my application char[2] might be in use so therefore I need to use position 3 in the char array. I would then end up with this:

char store[3][10];

But keeping the data originally store in:

char store[0][10];
char store[1][10];
char store[2][10];

Solution

  • You should dynamically allocate memory for the array using standard C functions malloc and realloc declared in header <stdlib.h>.

    Here is a demonstrative program that shows how the memory can be allocated.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define N   10
    
    int main(void) 
    {
        size_t n = 2;
        char ( *my_test )[N] = malloc( n * sizeof( char[N] ) );
    
        strcpy( my_test[0], "first" );
        strcpy( my_test[1], "second" );
    
        for ( size_t i = 0; i < n; i++ ) puts( my_test[i] );
    
        putchar( '\n' );
    
        char ( *tmp )[N] = realloc( my_test, ( n + 1 ) * sizeof( char[N] ) );
    
        if ( tmp != NULL )
        {
            my_test = tmp;
            strcpy( my_test[n++], "third" );
        }
    
        for ( size_t i = 0; i < n; i++ ) puts( my_test[i] );
    
        free( my_test );
    
        return 0;
    }
    

    The program output is

    first
    second
    
    first
    second
    third