gpt4 book ai didi

c - 将二维数组传递给函数

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:59 24 4
gpt4 key购买 nike

我已经能够想出以下将二维数组发送到函数的方法:

#include <stdio.h>

# define NUM_TWO_DIM_ROWS 3
# define NUM_TWO_DIM_COLS 5

void iterate_two_dim(int[][NUM_TWO_DIM_COLS]);
void iterate_two_dim1(int (*)[NUM_TWO_DIM_COLS]);
void iterate_two_dim2(int *);

int main() {

int two_dim[][NUM_TWO_DIM_COLS] = { //note the second dimension needs to be specified to resolve expression like two_dim[1]
{1,2,3,4,5}, // second dimension tells how many integers to move the two_dim pointer
{6,7,8,9,10},
{11,12,13,14,15}
};

iterate_two_dim(two_dim);
iterate_two_dim1(two_dim);
iterate_two_dim2(*two_dim);


}

void iterate_two_dim(int two_dim[][NUM_TWO_DIM_COLS]) { //function parameter uses array notation
printf("Two dim array passed using array notation\n" );
for(int row = 0; row < NUM_TWO_DIM_ROWS; row++) {
for(int col = 0; col < NUM_TWO_DIM_COLS; col++) {
printf("two_dim[%d][%d] = %-4d ", row,col, two_dim[row][col] );
}
printf("\n");
}
printf("\n");
}

void iterate_two_dim1(int (*two_dim)[NUM_TWO_DIM_COLS]) { //function parameter uses pointer notation
printf("Two dim array passed using pointer notation\n" );
for(int row = 0; row < NUM_TWO_DIM_ROWS; row++) {
for(int col = 0; col < NUM_TWO_DIM_COLS; col++) {
printf("two_dim[%d][%d] = %-4d ", row,col, two_dim[row][col] );
}
printf("\n");
}
printf("\n");
}

void iterate_two_dim2(int *two_dim) { //function parameter uses pointer notation
printf("Two dim array passed using pointer notation\n" );
char buffer[100];
for(int count = 0; count < NUM_TWO_DIM_ROWS * NUM_TWO_DIM_COLS; count++) {
if(count > 0 && count % NUM_TWO_DIM_COLS == 0 )
printf("\n");
snprintf(buffer, 40, "two_dim[%d] = %2d", count, two_dim[count] );
printf("%-20s", buffer );
}
printf("\n");
}

对于声明和初始化数组 two_dim 的这段代码,还有其他方法吗?

最佳答案

方法 1 和方法 2 相同(并且是正确的)。 array of type 的参数调整为 pointer to type 类型的参数,即 int[][NUM_TWO_DIM_COLS] 变为 int (*two_dim)[NUM_TWO_DIM_COLS] 调整后。


方式3是错误的。您正在越界访问数组。允许编译器考虑到指针指向 NUM_TWO_DIM_COLS 数组的第一个元素,并对这个边界进行边界检查。

C11 Appendix J.2将此列为未定义的行为:

An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

关于c - 将二维数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54759781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com