c - 为什么我的函数没有真正初始化数组?

标签 c arrays function multidimensional-array

我正在尝试编写一个将数组初始化为零的函数:

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/

相关文章:

使用文件输入和输出的 C 程序结构

c - 从 Go 代码修改 C void* 字节数组

python - 计算数组中特定字母的数量

arrays - 最快查找已知静态整数集?

C : program to calculate GPA for students

c - C 中的 rand() 输出不在指定范围内的数字

java - 在java中传输二进制文件(数据)

python - 将类放在其他类的静态数组中

function - 柯里化(Currying)一个函数以获得另一个函数 : unit -> 'a

javascript - 这是合法的javascript吗?将参数传递给函数并让它改变它们