簡體   English   中英

c++ 指針數組和 memory 地址分配

[英]c++ array of pointers and memory address allocation

有人可以解釋如何動態實現 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

有人可以解釋指針 arrays 的整個混亂。

我假設您想對動態數組執行操作,例如添加元素和打印; 記住:在 int *ptr=new int[5]; sizeof(ptr) 是堆棧 memory 上的 8 個字節,數組將存儲在堆 memory 中。

我們將通過指針 ptr 獲取元素,每個元素都將根據數組的類型(比如 int )獲取,然后 ptr 將 go 到第 0 個索引元素並將其數據讀取為 int 類型(只有 4 個字節,因為 int 是 4 個字節一般)並移動到下一個索引直到結束。 查看下面的代碼:

#include <iostream>
using namespace std;

int main() {
int *ptr=new int[5]; //let size = 5
for(int i=0; i<5;i++){
cin>>ptr[i];
}
for(int i=0; i<5;i++){
cout<<&ptr[i]<<":";  //this will print every element's address per iteration
cout<<ptr[i]<<endl;  //this will print every element as per input you gave
}
delete []ptr; //remember it's not delete ptr ask if required
return 0;
}

現在看到 output 自己試運行就可以理解了

Output

0x556999c63e70:1
0x556999c63e74:2
0x556999c63e78:3
0x556999c63e7c:4
0x556999c63e80:5

動態數組的好處是您可以根據用戶選擇通過輸入大小來創建動態大小的數組,通過該變量是動態數組的大小,即您可以將大小 = 5 更改為“N”一個變量。

我認為這可能會對您有所幫助,否則您可以要求進一步澄清。

在此處輸入圖像描述

如果有人對指針數組概念與動態分配指針數組到新的 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM