简体   繁体   English

对二维数组使用 scanf 时出现 C 分段错误

[英]C Segmentation Fault While using scanf for 2D array

As suggested by a book of "Gottfried", I tried to input an array and display the contents of array in matrix form :正如一本书“Gottfried”所建议的那样,我尝试输入一个数组并以矩阵形式显示数组的内容:

#include<stdio.h>

#define row 2
#define col 3

int main(){
    int (*a)[col];
    int i,j;

    for(i=0;i<row;i++){
        for(j=0;i<col;j++){
            printf("Enter a(%d,%d)",i,j);
            scanf("%d",(*(a+i)+j));
        }
    }

    return 0;
}

I get the following output after inputting an element :输入元素后,我得到以下输出:

Segmentation fault (core dumped)分段错误(核心转储)

What is the problem in the code?代码中有什么问题? Was it working in previous version of GCC so the writer wrote it down?它是否在以前版本的 GCC 中工作,因此作者将其写下来? What is the correct way to solve the problem with the same level of simplicity?以相同的简单程度解决问题的正确方法是什么?

As it was pointed out in the comments it is not a 2D array, but a 1D array of pointers.正如评论中指出的那样,它不是二维数组,而是一维指针数组。 Also in the second for loop you accidently use i<col instead of j<col .同样在第二个 for 循环中,您不小心使用i<col而不是j<col This will work这将工作

#include<stdio.h>

#define ROW 2
#define COL 3

int main(){
    int a[ROW][COL];
    int i, j;

    for(i = 0; i < ROW; i++){
        for(j = 0;j < COL; j++){
            printf("Enter a(%d,%d)", i, j);
            scanf("%d", (*(a + i ) + j));
        }
    }
    return 0;
}

If you want to declare a as a pointer to an array of col int s, as it's done in this line如果要将a声明为指向col int数组的指针,就像在这一行中所做的那样

int (*a)[col];

Then you should also allocate (and ultimately free) the memory needed, before trying to use it.然后,在尝试使用它之前,您还应该分配(并最终释放)所需的内存。

a = malloc(sizeof(*a) * row);
if (!a)
    exit(1);
// ...
free(a);

The posted code also have another issue in the nested loops发布的代码在嵌套循环中还有另一个问题

for (i = 0; i < row; i++) {
    for (j = 0; i < col; j++) {
//              ^^^^^^^           It should be 'j < col'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM