[英]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.