代码结果说明

Explanation of code result

你能给我解释一下为什么这段代码中二维数组的第一个元素是1吗?

#include <stdio.h>
#include <stdlib.h>
   int main(void) {
       int i,j;
       int **p = (int **)malloc(2 * sizeof(int *));
       p[0] = (int *)malloc(2 * sizeof(int));
       p[1] = p[0];
       for(i = 0; i < 2; i++)
               for(j = 0; j < 2; j++){
                   printf("i=%d & j=%d\t",i,j);
                   p[i][j] = i + j;
                   printf("p[%d][%d]=%d\n",i,j,p[i][j]);
                   printf("this is the result of the first element %d\n",p[0][0]);
               }


       printf("this is the result %d\n",p[0][0]);
       return 0;
   }

结果是:

i=0 & j=0 p[0][0]=0

this is the result of the first element 0

i=0 & j=1 p[0][1]=1

this is the result of the first element 0

i=1 & j=0 p[1][0]=1

this is the result of the first element 1

i=1 & j=1 p[1][1]=2

this is the result of the first element 1

this is the result 1

Press to close this window...

因为p[0]p[1]这两行确实是一样的

p 是两个指针的数组:

int **p = (int **)malloc(2 * sizeof(int *));

第一个指向大小为 2 的数组:

p[0] = (int *)malloc(2 * sizeof(int));

第二个指向同一个数组:

p[1] = p[0];

所以对 p[1][0] 的任何修改都会反映在 p[0][0] 上,因为两者都引用内存中的相同位置。正如您可以验证的那样,您将 1 分配给了 p[1][0],因此 p[0][0] 也变成了 1

我试图在图中解释(抱歉,但它更容易)。

因此,为了更正您的错误并声明一个正确的二维矩阵,将 p[0] 的 malloc 写成 for(int i=0; i < 2;i++)p[i] = (int *)malloc(2*sizeof(int));.