[英]Segmentation Fault within but unsure how to fix
目前正在尝试处理此代码以查找错误以及如何修复它们并首次学习如何使用 GDB,
int Find11();
void PointersAreFun();
int main(void) {
int myArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int found = Find11();
if (found != -1) {
printf("The number 11 is in the table at location: %d\n", found);
} else {
printf("The number 11 is not in the table.\n");
}
PointersAreFun(myArray, 10);
return 0;
}
int Find11(void) {
int i = 0;
int count = 0;
int search = 1;
int found = -1;
int number = 5;
int table[10];
table[0] = number;
printf("table[%i]: %i\n", count, table[count]);
count = 1;
while (count < 10) {
table[count] = number++ * 2;
printf("table[%i]: %i\n", count, table[count]);
count++;
}
while (search = 1) {
if (table[i++] == 11) {
search = 0;
found = -1;
}
if (count == i) {
search = 0;
found = 0;
}
}
return found;
}
void PointersAreFun(int myArray[], int size) {
printf("\nDemo on Pointers!\n");
int anotheArray[10] = {10, 11, 12};
int *ptrArray = NULL;
int *ptrAnotherArray = NULL;
ptrArray = myArray;
printf("The first value of the array is %d\n", *ptrArray);
printf("The first value of the second array is %d\n", *ptrAnotherArray);
}
我已经确定了这段代码周围的分段错误
while (search = 1) {
if (table[i++] == 11) {
search = 0;
found = -1;
}
if (count == i) {
search = 0;
found = 0;
}
}
但我不确定如何解决这个问题,因为变量 i 似乎继续增加,永远跳过 if(count == i),就像在 GDB 调试器中一样,即使计数为 10 并且变量 i 等于 10,它也会继续增加。 跳过第二个 if 条件
在您的代码中:
while( search = 1 )
您必须使用==
将search
与1
进行比较
还有一件事
int * ptrAnotherArray = NULL;
printf("The first value of the second array is %d\n", *ptrAnotherArray);
您设置指针 == NULL
然后打印它指向的值。 它使段错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.