完全披露:这是我有错误的家庭作业。
我接收到神秘的间歇性段错误 - 就在printf(...,pas_isin(thelist,5)
之后但在下一个printf
之前。或者至少是输出结果的含义 - 我猜它可能会在pas_isIn
内的某处终止,并且STDOUT不会被刷新。
printf("\n\nTesting isIn with 5 - should return 1");
printf("\npas_isIn returned %i",pas_isIn(thelist,5));
printf("\n\nTesting isIn with 10000 - should return 0");
printf("\npas_isIn returned %i",pas_isIn(thelist,10000));
此处pas_isIn()
:
//returns true if the given list contains the given value
int pas_isIn(int thelist[], int x) {
int t;
int length;
//empty list dont' contain much of anything
if (pas_isEmpty(thelist)) { return 0; }
for (t=1; t <= length; t++) {
if (thelist[t]==x) { return 1; }
}
return 0;
}
该列表是一个数组,分配大小为50,并且在调用时包含大约四个值。列表中的第一个值是数组中的值的数量。有什么想法吗?
答案 0 :(得分:3)
length
未在您的代码中初始化,似乎您将数组的长度存储在它的第一个元素中,所以这应该这样做
//returns true if the given list contains the given value
int pas_isIn(int thelist[], int x) {
int t;
int length;
length = thelist[0];
//empty list dont' contain much of anything
if (pas_isEmpty(thelist)) { return 0; }
for (t=1; t <= length; t++) {
if (thelist[t]==x)
return 1;
}
return 0;
}
int
类型的未初始化变量可能包含任何值,对于thelist
数组而言可能太大。