【问题标题】:can someone help me to find the bug which results in Segmentation fault (core dumped)?有人可以帮我找到导致分段错误(核心转储)的错误吗?
【发布时间】:2018-06-23 06:17:00
【问题描述】:

注意:实际上问题是以之字形方式打印矩阵的对角线 给定一个二维矩阵,以对角线顺序打印给定矩阵的所有元素。例如,考虑以下 5 X 4 输入矩阵。

 1     2     3     4  
 5     6     7     8  
 9    10    11    12  
13    14    15    16  
17    18    19    20 

上述矩阵的对角线打印为

1  
5   2  
9   6   3  
13  10  7   4  
17  14  11  8  
18  15  12  
19  16  
20  

现在我只是打印数组的下标

#include<stdio.h>
#include<stdlib.h>
int main(){
   int rows,cols,ind,inner,outer;
    scanf("%d %d",&rows,&cols);
   int **ptr=(int**)malloc(rows*sizeof(int*));
   for(ind=0;ind<rows;ind++)
          *(ptr+ind)=(int*)malloc(cols*sizeof(int));
for(outer=0;outer<cols;outer++){
         for(inner=0;inner<rows;inner++){
                  scanf("%d ",(*(ptr+outer)+inner));
            }
     }
inner=0,outer=0;
for(ind=1;ind<rows+cols;ind++){
     printf("%d",ind);
    while(*(*(ptr+outer)+inner)!=0)    {
            printf("%d %d",outer,inner);
               inner++;
            outer--;
            }printf("\n");
    }
    return 0;
}

也适用于没有 malloc 的数组

#include<stdio.h>
#include<stdlib.h>
int main(){
    int rows,cols,ind,inner,outer;
    scanf("%d %d",&rows,&cols);
    int arr[rows][cols];
    for(outer=0;outer<rows;outer++){
        for(inner=0;inner<cols;inner++){
            scanf("%d ",&arr[outer][inner]);
        }
    }
    inner=0,outer=0;
    for(ind=0;ind<rows;ind++){
    printf("%d",ind);
    while(arr[outer][inner]){
        //printf("%d %d",outer,inner);
        inner++;
        outer--;
        }
    printf("\n");
    outer=ind;
    inner=0;
    }
    return 0;
}

【问题讨论】:

标签: c arrays pointers segmentation-fault


【解决方案1】:

首先,不需要转换malloc(),请阅读此Do I cast the result of malloc?。

int **ptr=malloc(rows*sizeof(*ptr));
for(ind=0;ind<rows;ind++)
     *(ptr+ind)=malloc(cols*sizeof(**ptr));

当你为ptr[rows][cols]而不是ptr[cols][rows]分配内存时,外部for循环应该旋转rows次,内部for循环应该旋转cols次。

改成这样

for(outer=0;outer<rows;outer++){
    for(inner=0;inner<cols;inner++){ 
        scanf("%d ",(*(ptr+outer)+inner)); 
    } 
}

【讨论】:

  • 你为什么要做outer--?它会导致分段错误。应该是outer++。要检查元素是否为 NULL,您的条件是否正确。
  • 我只使用了 outer-- 和 inner++ 将控制器从 (1,0) 移动到 (0,1) 。
  • outer 初始值为0,ptr[-1][1] 是什么?当outer=-1 和inner=1。您需要相应地更改条件。
  • 花点时间阅读帮助中心的editing help。 Stack Overflow 上的格式与其他网站不同。
  • 我认为条件 (arr[outer][inner]) 会在 arr[-1][1] 时为假。
猜你喜欢
  • 1970-01-01
  • 2022-08-23
  • 2022-01-02
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
  • 2014-08-04
  • 2012-11-19
  • 1970-01-01
相关资源
最近更新 更多