gpt4 book ai didi

c - C 中的段错误(核心转储)错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:56:41 25 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序来对两个复数进行求和和减法。这是代码:

#include <stdlib.h>
#include <stdio.h>

typedef struct cplx
{
int re;
int im;
} cplx;

cplx* sum(cplx *x, cplx *y,int n)
{
cplx *z; int i;
for(i=0;i<n;i++)
{
z[i].re=x[i].re+y[i].re;
z[i].im=x[i].im+y[i].im;
}
return z;
}

cplx* difference(cplx *x, cplx *y, int n)
{
cplx *z; int i;
for(i=0;i<n;i++)
{
z[i].re=x[i].re-y[i].re;
z[i].im=x[i].im-y[i].im;
}
return z;
}

cplx* sumdiff(cplx *x,cplx *y, int n,cplx* (*op)())
{
return(op(x,y,n));
}

int main(void)
{
cplx *z1,*z2,*s,*diff;
int m,n,i;
printf("Give the number of complex numbers to add and substract:");
scanf("%d",&n);
z1=(cplx*)malloc(n*sizeof(cplx));
z2=(cplx*)malloc(n*sizeof(cplx));
s=(cplx*)malloc(n*sizeof(cplx));
diff=(cplx*)malloc(n*sizeof(cplx));
if ( z1==NULL || z2==NULL || s==NULL || diff==NULL)
{
printf("Allocation failed.\nEnding program.");
exit(0);
}
printf("Give the numbers of the first vector:\n");
for(i=0;i<n;i++)
{
printf("Re(z1[%d])=",i+1); scanf("%d",&m);
z1[i].re=m;
printf("Im(z1[%d])=",i+1); scanf("%d",&(z1[i].im));
}
printf("Give the numbers of the second vector:\n");
for(i=0;i<n;i++)
{
printf("Re(z2[%d])=",i+1); scanf("%d",&(z2[i].re));
printf("Im(z2[%d])=",i+1); scanf("%d",&(z2[i].im));
}
s=sum(z1,z2,n);
diff=difference(z1,z2,n);
s=sumdiff(z1,z2,n,sum);
diff=sumdiff(z1,z2,n,difference);
for(i=0;i<n;i++)
{
printf("z1[%d]+z2[%d]=%d+j(%d)\nz1[%d]+z2[%d]=%d+j(%d)\n",i+1,i+1,s[i+1].re,s[i+1].im,i,i,diff[i+1].re,diff[i+1].im);
}
free(z1); free(z2); free(s); free(diff);
return 0;
}

它用 GCC 编译得很好,但是当我运行它时,执行在 s=sum(z1,z2,n) 之前停止;出现段错误(核心已转储)。我做错了什么?

最佳答案

sumdifference 中的

z 是未初始化的指针。当您尝试写入此内容时,您会遇到未定义的行为(并且可能会崩溃)。您需要在每个函数中为 z 分配内存。

cplx* sum(cplx *x, cplx *y,int n)
{
cplx *z = malloc(n * sizeof(*z));
int i;
if (z == NULL) {
return NULL;
}

您还必须确保释放 从这些函数返回的内存。代码

s=sum(z1,z2,n);
diff=difference(z1,z2,n);
s=sumdiff(z1,z2,n,sum);
diff=sumdiff(z1,z2,n,difference);

目前会泄漏 sdiff

的第一个实例

关于c - C 中的段错误(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16575323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com