c - 内部分段错误但不确定如何修复
问题描述
目前正在尝试处理此代码以查找错误以及如何修复它们并首次学习如何使用 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
然后打印它指向的值。它使段错误
推荐阅读
- delphi - 在 Delphi 中不使用约束的情况下如何判断泛型类型是否为 nil?
- java - 如何捕获控制台中显示的断言错误
- javascript - 从一个客户端向另一个 socket.io 发送响应消息时出现问题
- go - Golang 从 openpgp.js 解密 PGP
- sql-server - 寻求对 SQL Server 索引问题的确认
- javascript - 创建一个适用于 vue 和 express 端的 NPM 模块
- c++ - wxGenericDirCtrl 错误“wxTheFileIconsTable 为 nullptr”
- reactjs - 如何在 Material-UI Grid 项目之间应用边距?
- xslt - 忽略每个 XSL 的阻塞
- jdbc - 自定义连接器中 JDBC 驱动程序的 Tableau 驱动程序解析器定义