【问题标题】:2 Dimension Arrays memory segment fault in C++C ++中的2维数组内存段错误
【发布时间】:2021-02-05 07:06:59
【问题描述】:

我用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++ arrays segmentation-fault


    【解决方案1】:

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

    【讨论】:

    • 我是非编程专业的。而且我是一个初学者,不到 3 个月的 C++ 编程经验,所以谢谢你的帮助。我还从答案中了解到我问的问题是多么愚蠢。但是当我自己编写代码时,我什至不知道这很愚蠢。谢谢你,有经验的编码程序员。
    • @wkCHO 不要对自己太苛刻。你的代码写得很好,你犯的错误是很多初学者都会犯的。
    猜你喜欢
    • 2013-05-27
    • 2020-06-15
    • 1970-01-01
    • 2016-05-07
    • 2014-06-15
    • 2015-10-08
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    相关资源
    最近更新 更多