我正在尝试编写一个将数组初始化为零的函数:
void InitializingToZero(int numOfrows, int numOfcols, int array[][20]) {
for (int i = 0; i < numOfrows; i++) {
for (int j = 0; j < numOfcols; j++) {
array[i][j] = 0;
}
}
}
int main() {
int num_of_rows = 3;
int num_of_cols = 3;
int array[num_of_rows][num_of_cols];
InitializingToZero(num_of_rows, num_of_cols, array);
for (int i = 0; i < num_of_rows; i++) {
for (int j = 0; j < num_of_cols; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
}
我得到这个输出:
0 0 0
0 0 0
268501009 0 4200656
最佳答案
错误是
int num_of_rows = 3;
int num_of_cols = 3;
然后您传递列字段为 20
的数组。因此,数组未正确初始化。这就是问题所在。
你应该这样做
void InitializingToZero(int numOfrows, int numOfcols, int array[][numOfcols]) {
how can i do it if just know that the max size of the array it's can be 20x20, and the numOfrows, numOfcols are inputs from the user?
然后你这样做
#define MAXSIZE 20
int array[MAXSIZE ][MAXSIZE];
..
InitializingToZero(num_of_rows, num_of_cols, array);
函数是
void InitializingToZero(int numOfrows, int numOfcols, int array[][MAXSIZE]) {
关于c - 为什么我的函数没有真正初始化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47961018/