首页 > 解决方案 > 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) 函数中遇到了段错误错误,我不知道是否有人可以提供帮助?

标签: c++arrayssegmentation-fault

解决方案


所以问题是你永远不会从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


推荐阅读