题
为什么下面的代码会给我一个分段错误?
#define MAXROWS 10
#define MAXCOLS 10
void getInput (int *data[MAXROWS][MAXCOLS]) {
int rows, cols;
int curRow, curCol;
printf ("How many rows and cols?");
scanf ("%d %d", rows, cols);
for (curRow = 0; curRow < rows; curRow++) {
for (curCol = 0; curCol < cols; curCol++) {
scanf ("%d", data[curRow][curCol]);
printf ("%d\n", *data[curRow][curCol]);
}
}
}
void main () {
int data[MAXROWS][MAXCOLS];
getInput (data);
}
似乎 scanf
和 printf
语句没有传入正确的数据类型,但我无法弄清楚他们应该。
如何更改它以使其正常工作?
解决方案
这声明了一个 MAXROWS
数组,指向 int
的指针。
int *data[MAXROWS][MAXCOLS];
但是,在函数定义中,顶级数组(任何大小)都等同于指针,因为数组在传递给函数时总是衰减到指向数组成员类型的指针。
所以你的函数定义相当于:
void getInput (int *(*data)[MAXCOLS])
即。一个指向 MAXCOLS
数组的指针,指向 int
。
正如您的代码所代表的那样,您永远不会初始化数组中的任何 int
指针,因为您将 int
的2d数组作为指向2d的指针传递 int *
的数组。
你可能想要传递的是一个指向 MAXCOLS
int
数组的指针:
void getInput (int (*data)[MAXCOLS])
或等效地:
void getInput (int data[][MAXCOLS])
然后执行以下操作:
int main(void)
{
int data[MAXROWS][MAXCOLS];
getInput(data);
return 0;
}
然后,您将2d数组作为指针传递给它的第一个元素(指向行的指针或 MAXCOLS
int
s的数组)。
如果您确定更改,请务必更改:
scanf ("%d", data[curRow][curCol]);
printf ("%d\n", *data[curRow][curCol]);
为:
scanf ("%d", &data[curRow][curCol]);
printf ("%d\n", data[curRow][curCol]);
另外,请在此处检查您的参数:
scanf ("%d %d", &rows, &cols);
您需要将指针传递给 rows
和 cols
。
确保在输入函数中添加一些边界检查,这样就不会尝试读取比 MAXROWS
或 MAXCOLS
更多的行和列。
其他提示
scanf接受变量的地址,而不是它的内容:
void getInput (int data[][MAXCOLS]) {
int rows, cols;
int curRow, curCol;
printf ("How many rows and cols?");
scanf ("%d %d", &rows, &cols);
//scanf ("%d %d", &rows, &cols);
for (curRow = 0; curRow < rows; curRow++) {
for (curCol = 0; curCol < cols; curCol++) {
scanf ("%d", &data[curRow][curCol]);
printf ("%d\n", data[curRow][curCol]);
}
}
}
有一些不同的问题。
首先,将数组传递给函数时,只需要定义N-1维。例如,如果您传递3D数组,则将最后2个维度的大小放在函数sig中,并将第一个维度留空。
foo(int threeD[][10][15]);
其次,scanf获取参数的地址,对于您的数组,该参数的地址如下所示
&data[curRow][curCol]
第三,你应该经常检查你输入的范围,以确保它是有效的:
if (rows > MAXROWS || cols > MAXCOLS) {
printf("Bad array dimensions\n");
return;
}
第四,总是在打开所有警告的情况下编译 - 编译器会警告你有关这些事情:
gcc -Wall pass_array.c -o pass_array
#include <stdio.h>
#define MAXROWS 10
#define MAXCOLS 10
void getInput (int data[][MAXCOLS]) {
int rows, cols;
int curRow, curCol;
printf ("How many rows and cols?");
scanf ("%d %d", &rows, &cols);
if (rows > MAXROWS || cols > MAXCOLS) {
printf("Bad array dimensions\n");
return;
}
for (curRow = 0; curRow < rows; curRow++) {
for (curCol = 0; curCol < cols; curCol++) {
scanf ("%d", &data[curRow][curCol]);
printf ("%d\n", data[curRow][curCol]);
}
}
}
int main () {
int data[MAXROWS][MAXCOLS];
getInput (data);
return 0;
}
不隶属于 StackOverflow