gpt4 book ai didi

c++ - 段错误 : 11 when using dynamic 3D array parameter

转载 作者:行者123 更新时间:2023-11-30 01:41:58 24 4
gpt4 key购买 nike

使用 gdb 查找段错误的来源我明白了

Program received signal SIGSEGV, Segmentation fault.
0x00000001000082bf in matchCounters (input=..., size=5,
valid_entries=0x100020cd0 <VALID_REGIONS>, nums=0x7fff5fbff460,
counters=0x100020588 <VTT for std::__1::basic_ifstream<char, std::__1::char_traits<char> >+8>) at akh70P3.cpp:524
524 cout << "counters[4][1] = " << counters[4][1] << endl;

主要()

double *** all_counters;
generateCounters(all_counters);
matchCounters(/*some more parameters here*/ all_counters[0]);

匹配计数器()

在此处访问计数器会导致段错误:11

void matchCounters(/*some more parameters here*/ double ** counters) {

//this causes segmentation fault 11
cout << "counters[4][1] = " << counters[4][1] << endl;
}

生成计数器()

在这里访问计数器工作得很好

void generateCounters(double *** all_counters) {
all_counters = new double ** [2];
//region counters
all_counters[0] = new double * [VALID_REGIONS_SIZE];
//move kind counters
all_counters[1] = new double * [VALID_MOVE_TYPES_SIZE];
for(int i = 0; i < VALID_REGIONS_SIZE; i++) {
all_counters[0][i] = new double [CATEGORIES];
}
for(int i = 0; i < VALID_MOVE_TYPES_SIZE; i++) {
all_counters[1][i] = new double [CATEGORIES];
}
//this works just fine! why?
cout << "all_counters[0][4][1] = " << all_counters[0][4][1] << endl;

}

最佳答案

all_counters = new double ** [2];

all_counters参数按值传递给 generateCounters() .

这会在动态范围内分配一个新数组,并将其分配给名为“all_counters”的参数,在名为“generateCounters()”的函数中.

all_counters在你的main()完全不受影响。

与其按值传递它,不如在 generateCounters() 中声明它, return它来自函数,并将其分配给 main() 中的变量.

关于c++ - 段错误 : 11 when using dynamic 3D array parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40391201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com