C编程:初始化一个数字为1,2,3等的二维数组

时间:2013-07-10 05:32:34

标签: c multidimensional-array user-input

我无法创建由用户定义的大小的2D数组,数字为1,2,3。等。

如果用户选择例如:a = 2 and b = 2,程序将生成:

3 4

3 4

而不是:

1  2

3  4

我的程序如下:

#include <stdio.h>

int main()
{
    int a = 0;
    int b = 0;
    int Array[a][b];
    int row, column;
    int count = 1;

/*User Input */
    printf("enter a and b \n");
    scanf("%d %d", &a, &b);

/* Create Array */
    for(row = 0; row < a; row++)
    {
        for(column = 0; column <b; column++)
        {
            Array[row][column] = count;
            count++;
        }
    }

/* Print Array*/
    for(row = 0; row<a; row++)
    {
        for(column = 0; column<b; column++)
        {
            printf("%d ", Array[row][column]);
        }
        printf("\n");
    }

    return 0;
}

4 个答案:

答案 0 :(得分:3)

int a, b;

变量ab未初始化且其值未通过C语言确定

int Array[a][b];

您声明一个具有[a,b]大小的数组。问题是a和b未确定,此时使用它们是未定义的行为。

scanf("%d %d", &a, &b);

您获得ab值 - 但Array保持不变!

最简单的解决方案:尝试在scanf之后放置数组声明。您的编译器可能允许它(我认为需要C99)。

答案 1 :(得分:1)

c89标准不支持可变长度数组。

int Array[a][b];毫无意义。因为当时ab的值未知。所以将其更改为Array[2][2]

答案 2 :(得分:1)

由于在编译时不知道您的数组大小,因此您需要在知道a和b之后动态分配数组。 代码如下:

int **allocate_2D_array(int rows, int columns)
{
    int k = 0;
    int **array = malloc(rows * sizeof (int *) );

    array[0] = malloc(columns * rows * sizeof (int) );
    for (k=1; k < rows; k++)
    {
        array[k] = array[0] + columns*k;
        bzero(array[k], columns * sizeof (int) );
    }

    bzero(array[0], columns * sizeof (int) );

    return array;
}

答案 3 :(得分:0)

由于您的数组大小在编译时是未知的,因此您需要在知道ab之后动态分配数组。

这是一个链接,描述了如何分配多维数组(实际上是一个数组数组):http://www.eskimo.com/~scs/cclass/int/sx9b.html

应用该链接的示例代码,您可以这样做:

int **Array; /* Instead of int Array[a][b] */

...

/* Create Array */
Array = malloc(a * sizeof(int *));
for(row = 0; row < a; row++)
{
    Array[row] = malloc(b * sizeof(int));
    for(column = 0; column <b; column++)
    {
        Array[row][column] = count;
        count++;
    }
}