【问题标题】:How to access values from a pointer-to-array in C++如何在 C++ 中访问指向数组的指针的值
【发布时间】:2021-11-18 15:12:26
【问题描述】:

我正在使用取消引用运算符,但我似乎没有得到 x 的值。

#include <iostream>
using namespace std;

class Array {

  public:
  int* get() {
      int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 

      int *r;
      r = x;
      return r;
  }
};

int main() {
  Array arr;

  int *temp = arr.get();

  for (int i = 0; i < 10; ++i) {
    cout << temp[i] << " ";
  }
}

这打印出 31 32765 0 0 0 0 -1989689609 32624 -989639072 32765 而不是 31 45 39 32 9 23 75 80 62 9

【问题讨论】:

标签: c++ arrays pointers


【解决方案1】:

您需要将其定义为类的私有成员

private:
    int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 

或者在函数内部时将其设为静态

static int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 

在这两种情况下,这个 x 数组都将保持不变,您将能够从中获取值。否则,您的 Get 函数将仅返回数组的第一个成员,而当退出函数范围时,其余成员将被清除。

【讨论】:

    【解决方案2】:

    当分配在堆栈上的变量超出范围时,它会被销毁。 在你的示例函数Array::get:

      int* get() {
          int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 
    
          int *r;
          r = x;
          return r;
      }
    

    变量x 被销毁。如果您不希望这种情况发生,您可以使用static 关键字标记您的变量:static int x[] = ... 或在堆上分配它int* x = new int[10]。如果您使用后者,请确保在不再使用内存时释放内存或使用智能指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 2016-02-20
      • 1970-01-01
      • 2012-06-07
      • 2011-08-10
      • 1970-01-01
      相关资源
      最近更新 更多