c中的2d动态int数组

问题描述 投票:1回答:1

我想创建一个函数,用一行增加给定的2d动态int数组。我看了几个网站,指南,教程,但一切都不一样,所以我现在很困惑。

2d阵列有2个固定列。

我的代码在这里:

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
}

我希望有人可以帮助我,并解释它是如何工作的!

对不起我的英语和错误的malloc / realloc知识。

c arrays multidimensional-array malloc realloc
1个回答
1
投票

函数参数是其局部变量。因此,在函数中,您处理原始参数的副本。

至少应该声明参数

int*** array

如果列数是编译时常量,则可以通过以下方式定义函数。

#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;
}

程序输出是

0   1
2   3
4   5
6   7
8   9
10  11
12  13
14  15
16  17
18  19
© www.soinside.com 2019 - 2024. All rights reserved.