简体   繁体   中英

2d dynamic int array in c

I would like to create a function which increase a given 2d dynamic int array with one row. I looked several website, guide, tutorial, but all is different, so I'm very confused now.

The 2d array has 2 fixed columns.

My code is here:

int length=1;
void arrayinc(int** array, int x0, int x1)
{
    if (array == NULL)
        malloc(array, sizeof(int[2]));
    else
        realloc(array, (++length)*sizeof(int[2]));

    array[length-1][0]=x0;
    array[length-1][1]=x1;

    free(array);
}

int main()
{
    int** array=NULL;
    arrayinc(&array, 1, 2);
    // I will do some stuff after the increase
}

I hope someone can help me, and explain how it really works!

Sorry for my english and bad malloc/realloc knowlage.

Function parameters are its local variables. So within the function you deal with a copy of the original argument.

At least the parameter shall be declared like

int*** array

If the number of columns is a compile-time constant then the function can be defined the following way.

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

#define N   2

size_t arrayinc( int ( **array )[N], size_t n, int x0, int x1)
{
    int ( *tmp )[N] = realloc( *array, ( n + 1 ) * sizeof( int[N] ) );

    if ( tmp )
    {
        *array = tmp;
        ( *array )[n][0] = x0;
        ( *array )[n][1] = x1;
        ++n;
    }

    return n;
}

int main(void) 
{
    int ( *array )[N] = NULL;
    size_t n = 0;

    for ( size_t i = 0; i < 10; i++ )
    {
        n = arrayinc( &array, n, ( int )( 2 * i ), ( int )( 2 * i + 1 ) );
    }

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d\t%d\n", array[i][0], array[i][1] );
    }

    free( array );

    return 0;
}

The program output is

0   1
2   3
4   5
6   7
8   9
10  11
12  13
14  15
16  17
18  19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM