Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 800
Ben Osborne Avatar asked Jun 24 '26 05:06

Ben Osborne


2 Answers

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
like image 69
Vlad from Moscow Avatar answered Jun 25 '26 19:06

Vlad from Moscow


char my_test[2][10];

is compile-time constant, which means that the required memory to use that array is carved to the stone already before your application starts. So you will never be able to change it's size.

You'll have to use DYNAMIC allocation. Check for something called malloc and free in case you are really working with C, or with C++ new and delete are what you need. You'll also need to learn about pointers.

like image 20
Simo Erkinheimo Avatar answered Jun 25 '26 18:06

Simo Erkinheimo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!