You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何从指向数组的指针取值?返回局部数组指针输出乱码如何解决

问题根因

你代码中get()函数内定义的int x[]属于局部自动变量,分配在栈内存空间。当get()函数执行结束后,对应的函数栈帧会被系统回收,这块内存的内容会被后续程序操作覆盖,你返回的指针r会成为悬空指针,后续通过temp访问该内存属于未定义行为,因此会输出乱码,仅第一个值因未及时被覆盖偶然显示正常。

正确实现方案

以下是三种可行的修复方案:

  • 方案1:将局部数组声明为静态存储类型
    静态变量分配在全局静态存储区,生命周期和程序运行周期一致,不会随函数返回被销毁。
#include <iostream>
using namespace std;

class Array {
public:
  int* get() {
      // 加static修饰
      static int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 
      return x;
  }
};

int main() {
  Array arr;
  int *temp = arr.get();
  for (int i = 0; i < 10; ++i) {
    cout << temp[i] << " ";
  }
}
  • 方案2:动态申请堆内存存储数组
    堆内存由开发者手动管理生命周期,只要不主动释放就会一直有效,注意使用完成后要手动释放避免内存泄漏。
#include <iostream>
#include <cstring>
using namespace std;

class Array {
public:
  int* get() {
      int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 
      // 动态申请堆内存
      int *r = new int[10];
      memcpy(r, x, sizeof(x));
      return r;
  }
};

int main() {
  Array arr;
  int *temp = arr.get();
  for (int i = 0; i < 10; ++i) {
    cout << temp[i] << " ";
  }
  // 手动释放堆内存
  delete[] temp;
  return 0;
}
  • 方案3:使用STL容器std::vector传递数据(最推荐)
    无需手动管理内存,符合C++现代开发规范,安全性最高。
#include <iostream>
#include <vector>
using namespace std;

class Array {
public:
  vector<int> get() {
      return { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 
  }
};

int main() {
  Array arr;
  vector<int> temp = arr.get();
  for (int num : temp) {
    cout << num << " ";
  }
  return 0;
}

内容的提问来源于stack exchange,提问作者Snorlax Mine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:57:01