[英]Store values in an array of pointers
我想将值存储在一个指针数组中。 到目前为止,我已经完成了以下操作,但它没有像我预期的那样工作:
#include <fstream> //for file IO (ifstream)
#include <iostream> //for cin >> and cout <<
using namespace std;
#define MAX_N 1000
int *ptr[MAX_N]; //It declares ptr as an array of MAX integer pointers
int myptr = 0;
int main() {
for (int i = 0; i < 3; i++)
{
myptr++;
}
ptr[0] = &myptr; // assign the address of integer
cout << *ptr[0] << endl;
for (int i = 0; i < 2; i++)
{
myptr++;
}
ptr[1] = &myptr; // assign the address of integer
cout << *ptr[1] << endl;
for (int i = 0; i <= 1; i++) {
cout << "Value of element " << i << ": " << *ptr[i] << endl;
}
return 0;
}
我想要最后一个循环输出:
Value of element 0: 3
Value of element 1: 5
但它给了我:
Value of element 0: 5
Value of element 1: 5
显然,我错过了一些东西。 这两个元素都指向我无法理解的同一个地址,因为变量myptr
改变了它的值。
谁能帮我这个?
谢谢
您只需让两个指针指向相同的 memory 地址即可。 您永远不会为更多int
分配额外的 memory,这就是为什么您总是读取当前存储在myptr
中的值。 要分配额外的 memory 使用new
并且不要忘记在最后释放所有新分配的 memory :
#define MAX_N 1000
// make sure the pointers are initialized as null pointers
int* ptr[MAX_N] { nullptr }; //It declares ptr as an array of MAX integer pointers
int myptr = 0;
int main() {
for (int i = 0; i < 3; i++)
{
myptr++;
}
ptr[0] = new int(myptr); // dynamically create an int with the value currently stored in myptr
cout << *ptr[0] << endl;
for (int i = 0; i < 2; i++)
{
myptr++;
}
ptr[1] = new int(myptr); // allocate another int
cout << *ptr[1] << endl;
for (int i = 0; i <= 1; i++) {
cout << "Value of element " << i << ": " << *ptr[i] << endl;
}
// free all the allocated ints (delete null doesn't hurt)
for (int* p : ptr)
{
delete p;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.