简体   繁体   English

使用整数指针的二维矩阵求和

[英]2-D matrix sum using pointer to integers

#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. 在此程序中,我声明了3个指向3个整数数组的指针。 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. 我尝试了很多,但是失败了。

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[i][j]有效。

Similarly you should allocate memory for each pointers individually. 同样,您应该分别为每个指针分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM