[英]Seg fault dynamically allocated 2d array
I have a homework assignment where I have to dynamically allocate a 2d array and i am getting seg faults when my arrays are long and skinny, such as 2x8, and the problem only occurs when certain values are in the array. 我有一个作业分配,其中我必须动态分配2d数组,并且当我的数组又长又瘦如2x8时,我会遇到段错误,并且仅在数组中有某些值时才会出现问题。 here is my code for making the array and then deleting it. 这是我制作数组然后删除它的代码。
int main()
{
int **p;
int w, h;
cin >> w >> h;
p= new int *[w];
for (int k=0; k<w; k++)
p[k]= new int[h];
for (int i=0; i<h; i++)
{
for(int k=0; k<w; k++)
{
cin >> p[i][k];
}
}
for (int k=0; k < w; k++)
delete []p[k];
delete []p;
return 0;
}
example input that causes seg fault:
8 2
5 4 2 3 0 1 2 5
2 0 1 0 9 6 3 2
Using gdb I found it is segfaulting right after the first delete in the loop. 使用gdb时,我发现它在循环中的第一次删除之后就存在段错误。
You have mixed up your indexes. 您混合了索引。 You allocate w
pointers, but your loop runs i
through h
elements. 您分配w
指针,但是循环通过h
元素运行i
。
The loops for assigning values have their boundaries swapped. 分配值的循环的边界被交换。
p
is given an array of length w
, but then the iterator i
which loops up to h
is used to index it. 给p
一个长度为w
的数组,但是循环到h
的迭代器i
用于对其进行索引。
p= new int *[w];
....
cin >> p[i][k];
p[i][k]
is read as p[i]
then indexed by [k]
. p[i][k]
被读取为p[i]
然后由[k]
索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.