首页 > 解决方案 > c++ 指针数组和内存地址分配

问题描述

有人可以解释如何动态地实现 c++ 的指针数组吗?

下面的代码正确吗?

如果是这样,

 int *ptr[5]; 

 for (int i = 0; i < 5; i++)
  {

  int size = 2;

  ptr[i] = new int [size] ;

 //*(ptr + i) = new int[size]; this is the same as above line

  cout << &ptr[i] << endl;   ----------> line 1
  cout << ptr[i] << endl; -----------> line 2
  }

第 1 行和第 2 行实际打印的是什么?

这是我在第 1 行得到的地址

0x7fff88f805d0
0x7fff88f805d8
0x7fff88f805e0
0x7fff88f805e8
0x7fff88f805f0

这是我在第 2 行得到的地址

0x55f946348ef0
0x55f946349330
0x55f946349360
0x55f946349390
0x55f9463493c0

有人可以解释这整个指针数组的混乱。

标签: c++arraysooppointersmemory-address

解决方案


在此处输入图像描述

如果有人对指针数组概念与动态分配指针数组到新的 int 或任何其他类型数组感到困惑,该图片提供了对该问题的图形解释


int *ptr[2]; // statically declared pointer array stack

    int p [2];

for (int i = 0; i < 2; i++)
      {
      int size = 2;

      ptr[i] = new int[size];
      cout << i << " array of int " << endl;
      //*(ptr + i) = new int[size];

      for (int j = 0; j < size; j++)
        {
        cout << "value : " ;
        cout << *(ptr[i] + j) ;  // <------- this should give 0's as value
        //cout << (ptr[i])[j] ; <------ same thing
        cout << "  address :";
        cout << ptr[i] + j << endl; //<----- these are in order as well since it's an array of type int

        }

      }
0 array of int 
value : 0  address :0x564c9ede32c0
value : 0  address :0x564c9ede32c4
value : 0  address :0x564c9ede32c8
1 array of int 
value : 0  address :0x564c9ede32e0
value : 0  address :0x564c9ede32e4
value : 0  address :0x564c9ede32e8

推荐阅读