0

I'm writing a program that reads in 30 numbers from a file stores them in an array then passes that array to a function which will print out only the even numbers from that array. However, I'm getting a Bad Access Code error in my while statement.

Any suggestions? Thanks in advance!

 #include <stdio.h>
void even(int numbers[]);

int main(int argc, const char * argv[]) {

    FILE *file = fopen("input.txt", "r");

    if (file == NULL) {
        printf("error");
    }

    int numbers[30];
    int num = 0;

    int i = 1;
    while(fscanf(file, "%d,", &num) > 0) {
        numbers[i] = num;
        i++;
    }

    fclose(file);

    even(numbers);

    return 0;
}

void even(int numbers[]){
    for (int i = 0; i < 30; i++) {
        if (numbers[i] %2 == 0) {
            printf("%d", numbers[i]);
        }
    }
}
2
  • 1
    while (fscanf(file, "%d, ", &num) > 0) is strictly wrong. Please read scanf(3). Commented Oct 23, 2015 at 17:13
  • printf("error"); --> printf("error");return -1; Commented Oct 23, 2015 at 17:36

1 Answer 1

2

Your code has mainly 3.5 issues

  1. You start with i = 1 in the first while loop.

    int i = 1;
    /*      ^ this should be 0 */
    while(fscanf(file, "%d,", &num) > 0)
    

    Since you start at 1 the 0th element is not initialized, yet you still try to read it (read before write) in even() and that, causes undefined behavior.

  2. You never check for i's value not to go beyond the number of elements in the array.

  3. You try to print 30 elements even though you might read less than that, you must count the total number of elements successfly read and pass that number to even(), or at least initialize the array to 0s.

  4. If fscanf() succeeds it returns the number of elements matched. This will not cuase a problem in your code but is strictly wrong.

I suggets the following simple fix

int i = 0;
while ((fscanf(file, "%d,", &num) == 1) && (i < 30))

And

void even(int numbers[], size_t count) {
    for (int i = 0 ; i < count ; i++) {
        if (numbers[i] %2 == 0) {
            printf("%d", numbers[i]);
        }
    }
}

don't write a function that you can't reuse, it makes no sense.

Sign up to request clarification or add additional context in comments.

1 Comment

fscanf would return zero when your input file has unexpected characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.