#include<stdio.h>
int main()
{
int (*p)[3],i,j;
int (*q)[3];
int (*r)[3];
printf("Enter 6 integers of first matrix:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",*(p+i)+j);
printf("The matrix you have entered is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf(" %d ", *(*(p+i)+j));
}
printf("\n");
}
printf("Enter 6 integers of second matrix:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",*(q+i)+j);
printf("The matrix you have entered is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf(" %d ", *(*(q+i)+j));
}
printf("\n");
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
*(*(r+i)+j)=*(*(p+i)+j) + *(*(q+i)+j);
}
}
printf("The summation matrix is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf(" %d ", *(*(r+i)+j));
}
printf("\n");
}
}
In this program I have declared 3 pointers to an array of 3 integers. when I execute, the first matrix works fine and displayed. However, when I enter integers for the second matrix it crashes. I tried a lot but it fails.
在这个程序中,我声明了3个指向3个整数数组的指针。当我执行时,第一个矩阵工作良好并显示出来。但是,当我为第二个矩阵输入整数时,它会崩溃。我试了很多,但是失败了。
1 个解决方案
#1
0
As you say you have a pointer , pointer should point to some memory location before writing something to it. In your case the pointer doesn't point to any valid memory location and hence the crash.
当你说你有一个指针时,指针应该在写东西之前指向某个内存位置。在这种情况下,指针不会指向任何有效的内存位置,从而导致崩溃。
If you want a 2*3 matrix then you should be having
如果你想要一个2*3矩阵那么你应该有
char *p[2];
p[0] = malloc(sizeof(int) *3);
Then
然后
p[i][j]
is valid.
p[我][j]是有效的。
Similarly you should allocate memory for each pointers individually.
同样,应该为每个指针单独分配内存。
#1
0
As you say you have a pointer , pointer should point to some memory location before writing something to it. In your case the pointer doesn't point to any valid memory location and hence the crash.
当你说你有一个指针时,指针应该在写东西之前指向某个内存位置。在这种情况下,指针不会指向任何有效的内存位置,从而导致崩溃。
If you want a 2*3 matrix then you should be having
如果你想要一个2*3矩阵那么你应该有
char *p[2];
p[0] = malloc(sizeof(int) *3);
Then
然后
p[i][j]
is valid.
p[我][j]是有效的。
Similarly you should allocate memory for each pointers individually.
同样,应该为每个指针单独分配内存。