c++ - 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
有人可以解释这整个指针数组的混乱。
解决方案
如果有人对指针数组概念与动态分配指针数组到新的 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
推荐阅读
- html - 从外部 HTML 显示视图
- php - 如何在php多维中搜索键值并返回仅包含搜索值的数组
- python - python:使用参考图像和来自相机的当前图像查找相机移位角度
- spring - 在 Spring-MVC 中使用会话
- antlr4 - Antlr4:使用属性值中的嵌套标记解析 JSP 标记
- amazon-web-services - Amazon CloudWatch:如何查找 CloudWatch 日志组的 ARN
- r - 如何按天汇总每个日期的每个实例?
- sql - 主键也是星型模式中的外键。是好是坏?
- javascript - 禁用拖放图像羽毛笔js
- python - Tweepy 只返回 1 条推文