我有这个代码:
#include <iostream>
#include <math.h>
int main()
{
int n,m,k,hours;
std::cin >> n >> m >> k;
hours = std::ceil(n * k / (float)m);
int* checkers = new int[m];
int** check = new int*[hours];
for(int i(0); i < hours; i++)
check[i] = new int[n];
for(int i(0); i < n; i++)
checkers[i] = (i + 1) % m;
std::cout << check[0][0];
return 0;
}
对于像20 4 1
这样的特定输入数据,当我试图打印check[0][0]时,它返回分段错误。但是如果我像这样替换int*checkers=new int[m];
:
#include <iostream>
#include <math.h>
int main()
{
int n,m,k,hours;
std::cin >> n >> m >> k;
hours = std::ceil(n * k / (float)m);
int** check = new int*[hours];
for(int i(0); i < hours; i++)
check[i] = new int[n];
int* checkers = new int[m];
for(int i(0); i < n; i++)
checkers[i] = (i + 1) % m;
std::cout << check[0][0];
return 0;
}
它将返回malloc.c:2394:sysmalloc:断言`(old_top==initial_top(av)&&old_size==0)((unsigned long)(old_size)>=MINSIZE&&prev_inuse(old_top)&((unsigned long)old_end&(pagesize-1))==0)'失败。
我该怎么修好呢?
附注。使用输入,例如3 1 1
,一切都很正常。
您在使用N
元素时为检查器
分配了M
元素。
要分配和使用的元素数量应该是匹配的(分配N
元素或使用M
元素,根据您要执行的操作)。
还要注意,new int[n]
的内容不是自动初始化的,因此您不能依赖check[0][0]
的值。