我正在尝试执行此代码,编译部分正常,前半部分也正常。我看不到我在哪里尝试访问未分配给数组的内存
#include <stdio.h>
int main(void){
int a[100], b[100], c[100], cont = 0, ind = 0, temp;
printf("Insert a integer number\n");
do{
printf("X = ");
scanf("%d", &temp);
if(temp >= 0)
a[cont] = temp;
cont++;
}
while(cont < 100 && temp > 0);
for(int i = 0; i < 100; i++){
for(int j = 0; j < 100; j++){
if(a[i] == b[j])
c[ind]++;
else{
b[ind] = a[i];
c[ind] = 1;
ind++;
}
}
}
printf("Exist %d different number in the list", ind);
for(int i = 0; i <= ind; i++){
printf("Number %d appears %d times", b[i], c[i]);
}
return 0;
}
最佳答案
您的变量 ind
可以增长到远远超过 100
,因此 a[ind]
(对于 b
也是类似的) , c
) 可以是越界访问。
当您在代码中编写 a[i] == b[j]
时,您正在读取未初始化的内存,因为您从未像 Ry- 中提到的那样初始化过 b
评论。
关于c - 如何修复 "Segmentation fault(core dumped)"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58511141/