这段代码能够正常运行,它会输出数组中的所有整数,但是会产生一个警告。我想知道如何正确地做并避免警告。
#include <stdio.h>
#include <stddef.h>
void print_all(int * array, ptrdiff_t num_rows, ptrdiff_t num_cols) {
for (ptrdiff_t i = 0; i < num_rows; ++i) {
for (ptrdiff_t j = 0; j < num_cols; ++j) {
printf("%d\n", array[num_cols * i + j]);
}
}
}
int main() {
int array[2][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8}
};
print_all(array, 2, 4);
}
这是警告信息:
$ clang -Wall -Wextra -pedantic -fsanitize=address -std=c11 arrays.c
arrays.c:18:15: warning: incompatible pointer types passing 'int [2][4]' to
parameter of type 'int *' [-Wincompatible-pointer-types]
print_all(array, 2, 4);
^~~~~
arrays.c:4:22: note: passing argument to parameter 'array' here
void print_all(int * array, ptrdiff_t num_rows, ptrdiff_t num_cols) {
^
1 warning generated.
让print_all
函数仅接受具有某些指定列数的数组是不可接受的。
int *
,而你正在传递一个int (*)[4]
。使用正确类型的指针调用函数print_all(array[0], 2, 4);
,以消除警告。你确定这是你想要保留的代码设计吗? - Bob__