【问题标题】:Store values in an array of pointers将值存储在指针数组中
【发布时间】:2021-02-17 19:40:24
【问题描述】:

我想将值存储在指针数组中。到目前为止,我已经完成了以下操作,但它并没有像我预期的那样工作:

#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 改变了它的值。

谁能帮我解决这个问题?

谢谢

【问题讨论】:

  • 您希望 myptr (&amp;myptr) 的地址发生变化吗?
  • 是的,这就是我想要的,但我做不到。我希望数组 ptr 包含不同的地址。并且这些地址应该对应&myptr的值。
  • 其实这个结果是预期的结果。您将 myPtr 变量的地址分配给 ptr[0] 并且值为 3,然后您将 myPtr 的地址再次分配给 ptr[1] 并且现在值为 5。结果 ptr[0] 和 ptr[1] 的地址是 myPtr ,值是 5。我想如果你想分配 myPtr 的地址,你不能取不同的值,因为它们有相同的地址。
  • 调用整数myptr 是一个有趣的创意选择
  • 当两个指针指向同一个对象时,它们在解除引用时都将显示相同的值。无论是用你的名字还是身份证上的号码来指代你,你都是同一个人。

标签: c++ arrays pointers


【解决方案1】:

你只需让两个指针指向同一个内存地址。你永远不会为更多的ints 分配额外的内存,这就是为什么你总是读取当前存储在myptr 中的值。要分配额外的内存,请使用new,并且不要忘记在最后释放所有新分配的内存:

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2016-02-12
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多