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

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

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

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

c arrays function multidimensional-array
3个回答
3
投票

错误是

int num_of_rows = 3;    
int num_of_cols = 3;

然后使用列字段20传递数组。因此,阵列未正确初始化。这就是问题所在。

你应该做这个

void InitializingToZero(int numOfrows, int numOfcols, int array[][numOfcols]) {

如果只知道数组的最大大小可以是20x20,而numOfrows,numOfcols是来自用户的输入,我该怎么办呢?

然后你这样做

#define MAXSIZE 20

int array[MAXSIZE ][MAXSIZE];

..


InitializingToZero(num_of_rows, num_of_cols, array);

功能就是

void InitializingToZero(int numOfrows, int numOfcols, int array[][MAXSIZE]) {

0
投票

我知道Quentin的反应是正确的,但为什么将内存区域设置为0这么复杂?

int main( void ) {
    const int COLS_AMOUNT = 3;
    static const int ROWS_AMOUNT = 3;

    int num_of_rows = ROWS_AMOUNT;
    int num_of_cols = ROWS_AMOUNT;
    int array[ROWS_AMOUNT][COLS_AMOUNT];

    /* Set to 0 */
    (void)memset( (void*)array, (int)0, sizeof( array ) );

    /* Then check previous set in decreasing order... */
    while( num_of_rows-- ) {
        while( num_of_cols-- ) {
            printf( "array[%d][%d]:%d ",
                    num_of_rows,
                    num_of_cols,
                    array[num_of_rows][num_of_cols] );
        }
        printf("\n");
    }
}

0
投票

通过将您的数组声明为

int num_of_rows = 3;    
int num_of_cols = 3;

int array[num_of_rows][num_of_cols];

您正在创建大小为[3][3]的可变长度数组(VLA)。但是函数参数被声明为数组[][20]

对于正确的数组参数传递,第一个大小无关紧要(因此空[]),但第二个(以及进一步,如果有的话)大小必须完全匹配。通过创建[3][20]之间的不匹配,你实际上是在骗你的功能。行为未定义。在VLA的情况下,编译器不能检测和报告这种不匹配,因为它们的实际大小在编译时通常是未知的。

代码中的问题很容易解决:只需将函数参数声明为正确大小的VLA即可

void InitializingToZero(int numOfrows, int numOfcols, 
                        int array[numOfrows][numOfcols])

并保持其他一切不变。 (第一个尺寸[numOfrows]可以像[]一样“空”,但为了更清晰,我决定拼出来。)

© www.soinside.com 2019 - 2024. All rights reserved.