SmOg3R
SmOg3R

Reputation: 294

Compiler reports "Segmentation fault: 11"

Here is my code:

#include <stdio.h>
#include <stdlib.h>

int main(){
    int noteven=0, n;

    printf("Input numbers, at the end write 0 \n");
    n=1;

    while(n!=0){
        scanf("%d", n);
            if (n%2==1){
                noteven++;
            }
    }
    printf("Not even numbers quantity: %d", noteven);
}

The error appears in terminal after inputting number. Can anyone please explain why this isn't working?

Upvotes: 0

Views: 77

Answers (2)

benipalj
benipalj

Reputation: 704

scanf needs the address where it can store the value it reads, so use it as follows:

scanf("%d", &n);

Upvotes: 2

Nathan Fellman
Nathan Fellman

Reputation: 127428

scanf requires a pointer to n:

scanf("%d", &n);

what this means is:

  1. scan a string from the keyboard
  2. interpret it as an integer (that's the %d)
  3. put it in the address of n (the & in &n means "the address of n)

without the &, what it says is:

  1. scan a string from the keyboard
  2. interpret it as an integer (that's the %d)
  3. take the value of n (currently uninitialized, so it holds garbage), and use that value as an address in memory, and store the number there.

Basically, you're telling scanf to write an integer in some random place in memory. You're lucky it only ended in a segmentation fault.

Upvotes: 2

Related Questions