Reputation: 51
I am new in C programming. When I write a c code about sorting integers. I got a Segmentation fault: 11. I search the related articles, but seems too confusing for me. Here follows first part of my code(get 10 input integers, and derive all the odd integers). Can you help me?
#include <stdio.h>
int i;
int main(void)
{
int array[10];
int previous[10],odd[10];
printf("Pls enter 10 nums\n");
while(i < 10)
{
scanf("%d", &array[i++]);
}
for(i = 0;i < 10;i++)
{
printf("%d ", array[i]);
}
for(i = 0;i < 10;i++)
{
int a,j;
if(array[i] % 2 == 1)
{
previous[a] = i;
odd[j] = array[i];
a++;
j++;
}
}
}
Upvotes: 0
Views: 74
Reputation: 1286
The problem is with the variables a
and j
. In C you cannot be sure that when you declare them they will have the value 0
.
Upvotes: 4
Reputation: 14941
If you don't give i
and a
initial values you will likely be attempting to go beyond the bounds of your array.
Upvotes: 1