有人可以帮我找到导致段错误(核心转储)的错误吗?

标签 c arrays pointers segmentation-fault

注意:实际上问题是以锯齿形方式打印矩阵的对角线 给定一个二维矩阵,按对角线顺序打印给定矩阵的所有元素。例如,考虑以下 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;
}

最佳答案

首先,不需要 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));

外部 for 循环应在分配时旋转 rows 次,内部 for 循环应在分配时旋转 colsptr[rows][cols] 的内存不适用于 ptr[cols][rows]

改变它就像

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

关于有人可以帮我找到导致段错误(核心转储)的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50998507/

相关文章:

c - 如果客户端无法应对(buffer++),如何停止写入套接字(AF_LOCAL/UNIX、SOCK_STREAM)?

c - 我什么时候必须添加空终止符?

c - 在字符串中查找前缀作为后缀

python - 根据给定坐标填充 2D Numpy 数组

c++ - 将现有数组的所有值设置为 "magic numbers"

java - 二叉堆类构造函数

c++ - 有什么方法可以检测指针是否指向数组?

c++ - 函数返回后如何删除堆分配的变量

c - 在 ubuntu 上读取、写入、更新 pci 卡上的 eeprom

c - 错误: invalid type argument of 'unary *' (have 'int' )|