C++编写返回指针的二进制转换函数运行出错,求错误原因解析
问题原因
- 核心错误:返回栈局部变量的指针
函数binary_con中定义的int binary[100]是存储在栈空间的局部变量,函数执行结束后该栈帧会被系统回收,对应的内存空间会被后续操作(比如输出函数调用)复用覆盖,你返回的指针实际是野指针,访问的内存值是不确定的脏数据,这是输出异常的核心原因。 - 遍历逻辑错误
你没有给转换后的二进制结果添加结束标记,且while(*a)的判断逻辑天然不适用:二进制结果本身就包含0值,同时数组未初始化的区域值是随机的,根本无法正确判断遍历的终止位置。
修复方案示例
更推荐使用C++风格的vector容器返回结果,不需要手动管理内存:
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> binary_con(int n) { vector<int> binary; while(n > 0) { binary.push_back(n % 2); n = n / 2; } // 反转得到高位在前的正常二进制顺序 reverse(binary.begin(), binary.end()); return binary; } int main() { int n; cout << "Input the number:"; cin >> n; vector<int> res = binary_con(n); for (int num : res) { cout << num; } return 0; }
如果一定要用指针返回的写法,改用new分配堆内存即可,记得使用完后手动delete释放避免内存泄漏:
#include <iostream> using namespace std; int* binary_con(int n, int& len) { int* binary = new int[100]; int i = 0; for (; n > 0; i++) { binary[i] = n % 2; n = n / 2; } len = i; // 传出有效长度,避免遍历错误 return binary; } int main() { int n, len; cout << "Input the number:"; cin >> n; int* a = binary_con(n, len); // 倒序输出得到高位在前的正常二进制顺序 for(int i = len - 1; i >= 0; i--) { cout << a[i]; } delete[] a; return 0; }
内容的提问来源于stack exchange,提问作者Yanbo Liu
相关产品推荐
相关产品推荐

