问题
I am having trouble creating a 2D Array of a size defined by the user, with numbers 1, 2, 3.etc.
If the user chooses for example: a = 2 and b = 2, the program produces:
3 4
3 4
instead of:
1 2
3 4
My program looks like:
#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;
}
回答1:
int a, b;
variables a and b are uninitialized and their value is undetermined by C language
int Array[a][b];
You declare an array which has [a,b] size. The problem is that a and b are undetermined and using them at this point is undefined behavior.
scanf("%d %d", &a, &b);
you get a and b values -- but the Array remains the same!
Simplest solution: try to put Array declaration after scanf. Your compiler may allow it (I think C99 is required to do so).
回答2:
Variable length array is not supported in c89 standard.
int Array[a][b]; is meaningless. Because values of a and b is unknown at that time. so change it to Array[2][2].
回答3:
Since your array size is not known at compile-time, you'll need to dynamically allocate the array after a and b are known. like code as follows:
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;
}
回答4:
Since your array size is not known at compile-time, you'll need to dynamically allocate the array after a and b are known.
Here's a link that describes how you can allocate the multi-dimensional array (really an array of arrays): http://www.eskimo.com/~scs/cclass/int/sx9b.html
Applying the example code from that link, you might do this:
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++;
}
}
来源:https://stackoverflow.com/questions/17563075/c-programming-initialize-a-2d-array-of-with-numbers-1-2-3-etc