c++ - C ++中的2维数组内存段错误
问题描述
我用cpp做了动态分配和数组初始化函数,但是出现分段错误我写的代码如下。
#include <iostream>
#define User_Height 100
#define User_Width 100
using namespace std;
void Creat_Array(int** _pp_Created_Array)
{
_pp_Created_Array = new int*[User_Width];
for (int x = 0; x < User_Height ; x++)
{
_pp_Created_Array[x] = new int[User_Height];
}
if(_pp_Created_Array == NULL)
{
cout<<"""fail to alloc memory.""" <<endl;
return;
}
else
{
cout << "[_pp_Created_Array] memory first address : ";
cout << _pp_Created_Array << endl << endl;
}
}
void Initialize_Array(int** _pp_Initialized_Array)
{
for (int x = 0; x < User_Width; x++)
{
for (int y = 0; y < User_Height; y++)
{
_pp_Initialized_Array[x][y] = 0; //*segment fault*
}
}
}
我检查了创建的函数函数
int main()
{
//debug
int** debugArray = nullptr;
cout << "start creat array" <<endl;
Creat_Array(debugArray);
cout << "start initial array" <<endl;
Initialize_Array(debugArray);
return 0;
}
和编译控制台是(VScode,g++)
start creat array
[_pp_Created_Array] memory first address : 0x8a6f40
start initial array
The terminal process "C:\Windows\System32\cmd.exe /d /c cmd /C
C:\Users\pangpany\project\PathfinderTest\main" failed to launch (exit code:
3221225477).
但是我在 void Initialize_Array(int** _pp_Initialized_Array) 函数中遇到了段错误错误,我不知道是否有人可以提供帮助?
解决方案
所以问题是你永远不会从Creat_Array
函数中返回数组。因此,当您使用数组时,您使用的是未初始化的变量。
Creat_Array
用返回值而不是参数写,像这样
int** Creat_Array()
{
int** _pp_Created_Array = ...;
...
return _pp_Created_Array;
}
int main()
{
cout << "start creat array" <<endl;
int** debugArray = Creat_Array();
...
}
更改函数内部的变量不会更改函数外部的任何变量。是两个不同的变量debugArray
。_pp_Created_Array
这个代码也是错误的
if(_pp_Created_Array == NULL)
new
永远不会返回NULL
,所以这个测试将永远是错误的。如果new
失败它会抛出一个异常,它不会返回NULL
。
推荐阅读
- django - 为什么我在 Django 中提交表单或刷新页面后页面没有重定向?
- c - Kernighan 和 Ritchie - 练习 3.3(扩展功能)
- r - 提高 profvis 性能以分析闪亮的应用程序
- javascript - JS indexOf 失败,总是返回-1
- apache-spark - Jupyter Notebook 如何与 Spark 集群通信
- leaflet - 传单和 WMS 版本 >= 1.3.0
- java - 有没有任何方法可以在没有任何连接的情况下检查日期是否正确(在没有篡改尝试的情况下)?
- flutter - 如何在渲染任何东西之前等待未来?
- lua - 如何在love2D中生成随机十进制数?
- json - 递归jsonSchema最大调用栈