[英]Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) memory allocation
I'm writing code for the addition of two matrics in Xcode Version 11.2 .我正在编写用于在 Xcode 版本 11.2 中添加两个矩阵的代码。 The display of the initial matrics works, but the addition of them doesn't.
初始矩阵的显示有效,但添加它们无效。 The error appears at the line
aloc3[i][j]=*(aloc1+i*m+j)+*(aloc2+i*m+j);
错误出现在
aloc3[i][j]=*(aloc1+i*m+j)+*(aloc2+i*m+j);
in "add" function.在“添加”功能中。 I really don't know what I have done wrong and I have spent hours to try to fix the problem , but nothing seem to fix it.
我真的不知道我做错了什么,我花了几个小时试图解决这个问题,但似乎没有任何解决办法。 Can someone help me?
有人能帮我吗?
#include <stdio.h>
#include <stdlib.h>
void add(int *aloc1,int *aloc2,int **aloc3,int m,int n);
void display(int *aloc,int m,int n);
int main() {
int *aloc1,*aloc2,*aloc3;
int m,n,i,j;
printf("\n Enter the number of rows : ");
scanf("%d",&m);
printf("\n Enter the number of colomns : ");
scanf("%d",&n);
if ((aloc1=(int*)malloc(n*m*sizeof(int))))
{
printf("\n Enter the elements of the first matrix: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",aloc1+i*m+j);
}
if ((aloc2=(int*)malloc(n*m*sizeof(int))))
{
printf("\n Enter the elements of the second matrix: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",aloc2+i*m+j);
}
printf("\n The initial matrics are: \n");
display(aloc1,m,n);
printf("\n \n");
display(aloc2,m,n);
add(aloc1,aloc2,&aloc3,m,n);
printf("\n The addition of the matrics is: \n");
display(aloc3,m,n);
return 0;
}
void add(int *aloc1,int *aloc2,int **aloc3,int m,int n)
{
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
aloc3[i][j]=*(aloc1+i*m+j)+*(aloc2+i*m+j);
}
void display(int *aloc,int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",*(aloc+m*i+j));
printf("\n");
}
}
You are passing a pointer to a single int*
to add
's aloc3
parameter.您将一个指向单个
int*
的指针传递给add
的aloc3
参数。 Therefore accessing it with aloc3[i]
for i>0
is undefined behavior, as aloc3
is not pointing to an array.因此,使用
aloc3[i]
for i>0
访问它是未定义的行为,因为aloc3
不指向数组。
You probably intended to write (*aloc3)[i*m+j]
, going by the indexing of the other parameters.您可能打算通过其他参数的索引来编写
(*aloc3)[i*m+j]
。
Even then, you never set aloc3
to any value in main
, nor do you set any value to *aloc3
in add
.即便如此,您也不会在
main
中将aloc3
设置为任何值,也不会在add
中将任何值设置为*aloc3
。 Thus (*aloc3)[i*m+j]
will be trying to dereference an indeterminate value, causing undefined behavior.因此
(*aloc3)[i*m+j]
将尝试取消对不确定值的引用,从而导致未定义的行为。
You seem to have forgotten a malloc
for alloc3
, either in add
or in main
.您似乎忘记了
alloc3
的malloc
,无论是在add
还是在main
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.