c - 当我尝试使用 realloc 将新行插入 2D-Array 时出现段错误

标签 c segmentation-fault multidimensional-array realloc

当程序在第一个元素的最后一个数字和最后一个元素的最后一个数字除以 2 中找到一行时,它应该将其他行添加到矩阵中。我需要使用动态分配来做到这一点。这是代码:

#include <stdio.h>
#include <malloc.h>

int **a;
int cifra(int n){

    int c=0;
    while (n)
    {
        c=n%10;
        n/=10;`
    }
    return c;
 }

 int conditie(int i, int m)
 {
     if(cifra(a[i][0])%2==0 && a[i][m-1]%2==0)
        return 1;
    return 0;`
 }

 int main()
 {
    int i,j,n,m,k,l;
    printf("n=");
    scanf("%d",&n);
    printf("m=");
    scanf("%d",&m);`

    a=(int**)malloc(n*sizeof(int*));
    a[0]=(int*)malloc(n*m*sizeof(int));

    for( i=1;i<n;i++)
        a[i]=a[i-1]+m;

    for(i=0;i<n;i++)
        for(j=0;j<m;j++)
            {
                printf("a[%d][%d]=",i,j);
                scanf("%d",&a[i][j]);
            }
    for(i=0;i<n;i++)
        if(conditie(i,m))
        {
           n++;
           a=(int**)realloc(a,n*sizeof(int*));
           for(k=n-1;k>i;k--)
               for (l=0;l<m;l++)
                    a[k][l] = a[k-1][l]; //the program seems to be crashing here
            for(j=0;j<m;j++)
                a[i+1][j]=-1;
        }
    for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
                {
                    printf("%d",a[i][j]);
                }
            printf("\n");
        }
    free(a[0]);
    free(a);
    return 0;
    }

最佳答案

这是你的问题。

for( i=1;i<n;i++)
    a[i]=a[i-1]+m;

您将任意指针分配给 a[i],当您引用它们时,它会引发段错误。

关于c - 当我尝试使用 realloc 将新行插入 2D-Array 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20273486/

相关文章:

c - return 语句中的递归

c++ - 具有相对超时的函数 pthread_rwlock_timedwrlock/timedrdlock

go - 如何防止在 Go 中初始化导出类型?

c++ - std::list of pointers 在条目删除时变得无效

c - 令人头疼的段错误

java - 二维字符串数组b 学生记录程序

c# - 如何使用 C# 按顺时针方向打印 4x4 数组

c - C宏的乐趣

php - 使用 array_multisort 对多维数组进行排序,其中您不知道数组的维度

c - 使用 fwrite() 将结构写入文件错误 688