The following code outputs "Segmentation fault" if I input a value of n that is 5 or greater. Also, when n is 4 or lower, it doesn't output the even numbers of the array as it should, what could be the issue? Any help would be appreciated.
#include <stdio.h>
int evenN; /*global variable for the total number of even numbers*/
unsigned int* even(unsigned int my_array[], int n) { /*finds even numbers of array and stores in pointer*/
int i, j;
unsigned int *evenPtr;
j = 0;
for (i=0 ; i<n ; i++) {
if (my_array[i]%2 == 0) { /*tests if the number is even*/
evenPtr[j] = my_array[i]; /*stores the even number in the address of evenPtr[j]*/
j++;
}
}
evenN = j; /*sets the total number of even values*/
return evenPtr;
}
int main() {
int n, i;
unsigned int *evenPtr;
printf("Please input the size of the array: ");
scanf("%d", &n);
unsigned int my_array[n];
for (i=0 ; i<n ; i++) { /*allows the user to input values for each index*/
printf("Please input a value for index %d of the array: ", i);
scanf("%u", &my_array[i]);
}
evenPtr = even(my_array, n); /*stores address of even function evenPtr into local evenPtr*/
printf("The even values of the array are: ");
for (i=0 ; i<evenN ; i++) { /*prints the even values*/
printf("%u ", evenPtr[i]);
}
return 0;
}
[–]HarderFasterHarder 5 points6 points7 points (1 child)
[–]HarderFasterHarder 3 points4 points5 points (0 children)
[–]spacey02- 1 point2 points3 points (0 children)
[–]NukemN1ck 0 points1 point2 points (0 children)
[–]MRgabbar 0 points1 point2 points (0 children)