简体   繁体   English

程序使用动态 memory 分配

[英]Program using dynamic memory allocation

I have the below program in C.我在 C 中有以下程序。 How did p[0][0] become 1? p[0][0]是怎么变成 1 的? Can somebody help in understanding?有人可以帮助理解吗?

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

main()
{
  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++)
     {
            p[i][j]=i+j;
            printf("%d,%d,%d",i,j,p[i][j]);
            printf("\n");
     }
 printf("%d,%d,%d",i,j,p[0][0]);
}

the output is as below output 如下

0,0,0
0,1,1
1,0,1
1,1,2
2,2,1

The same pointer is assigned to p[0] and p[1] .相同的指针分配给p[0]p[1] This means p[0] and p[1] points at the same array.这意味着p[0]p[1]指向同一个数组。 Therefore updates done via p[1] is also visible via p[0] .因此,通过p[1]完成的更新也可以通过p[0]看到。

In the second iteration of outer for loop, 1 is assigned to p[1][0] .在外部for循环的第二次迭代中,将1分配给p[1][0] This makes p[0][0] to be 1 .这使得p[0][0]1

After the following lines of code:在以下代码行之后:

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

this is what you have in memory:这就是 memory 中的内容:

   int **        int *           int
   +---+         +---+           +---+
p: |   | ------> |   | p[0] -+-> |   | p[0][0], p[1][0]
   +---+         +---+       |   +---+
                 |   | p[1] -+   |   | p[0][1], p[1][1]
                 +---+           +---+

p[0] and p[1] point to the same 2-element array, so anything you write to p[0][i] is reflected in p[1][i] and vice-versa. p[0]p[1]指向同一个 2 元素数组,因此您写入p[0][i]的任何内容都会反映在p[1][i]中,反之亦然。

What you probably meant to do was something like可能打算做的是

int **p = malloc( 2 * sizeof *p ); // cast not necessary, sizeof *p == sizeof (int *)
p[0] = malloc( 2 * sizeof *p[0] );
p[1] = malloc( 2 * sizeof *p[1] );

which would give you这会给你

   int **        int *            int 
   +---+         +---+            +---+
p: |   | ------> |   | p[0] ----> |   | p[0][0]
   +---+         +---+            +---+
                 |   | p[1] --+   |   | p[0][1]
                 +---+        |   +---+
                              |
                              |   +---+ 
                              +-> |   | p[1][0]
                                  +---+
                                  |   | p[1][1]
                                  +---+

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

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