c - 显示数组时c中的段错误

标签 c arrays

我必须采用“n”行字符数组(大小为m),其中只有数字,并且我必须将数字放入二维整数数组中。 我在第二次显示整数数组时遇到段错误。

int t,m,n,i,j,pix[182][182];
char ch,pixel[183];
scanf("%d",&t);
while(t--){

    scanf("%d %d",&n,&m);  //take n and m
    for(i=0;i<n;i++){
        printf("\n");
        scanf("%s",pixel); //take character array
        for(j=0;j<m;j++){ 
            pix[i][j]=pixel[j]-48;  //put numbers in integer array
            dis[i][j]=0;
            printf("%d ",pix[i][j]);  //no error here
        }
    }   
    for(i=0;i<n;i++){
        printf("\n");
        for(j=0;j<m;j++)
            printf("%d",pix[i][j]);  //segmentation fault after n-1 lines are displayed

问题是什么?

最佳答案

您的代码不会检查数组边界。在继续之前,您需要检查 mn 是否小于 182。您还应该使用一种方法来防止读取 pixel 数组时缓冲区溢出 - 例如 fgets(pixel, sizeof(pixel), stdin)。否则,根据 mn 的值,您可能会出现缓冲区溢出并产生不可预测的结果。

您的示例也没有显示 dis 数组的定义,但您还需要在那里进行边界检查。

除此之外,我猜测您的输入的布局与程序预期的不太一样。执行数组边界检查并在失败后立即断言将帮助您更快地找到差异。

关于c - 显示数组时c中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37685346/

相关文章:

objective-c - ATOI() 结果为 "Exited Unexpectedly/Lost Connection"

c - 使用 execlp() 遇到麻烦

jquery - 获取 D3 中数组的实际最大值

c++ - 在 Polymorph 设计中使用数组

php - 在php中从数组中获取结果

arrays - Julia:数组是否包含特定的子数组

c - 仅使用模数的 RSA 公钥转换

将结构成员写入内存的通用接口(interface)模式?

c - C 中两个数组元素地址之间的偏移量

arrays - 批处理 : Parsing out file path from dynamic array