Base converter - Segmentation fault (core dumped)

Asked

Viewed 54 times

0

I am trying to program a simple program that reads a number in base ten and converts it to binary and I have reached the following code:

#include <stdio.h>
#include <math.h>

int main(){
    int n;
    int c = 1;
    scanf("%d", n);
    while(n>=c){
        int digit = (n/c)%2;
        printf("%d", digit);
        c *= 2;
    }

}

I am aware that the number will be printed backwards, my problem is that after compiling the code (which happens without any error), the program always crashes when I try to open. When I used an online compiler, however, the output I got was "Segmentation fault (core dumped)". Can anyone explain to me what’s going on?

1 answer

1

Good afternoon @Christus,

The mistake mentioned by you: Segmentation fault (core dumped), happens when you try to access a memory improperly in your program, for example: If you allocate a vector of 10 spaces and try to access vet[100] its application will be finalized as a protection measure, so that no changes can be made to the programs that are running. More details about the Segmentation fault can be found in this answer.

I ran your code through a online compiler C and he accused the misuse of scanf().

In C we use the & to pass the address of variables to have their values changed, in the case of the example:

scanf("%d", n);

Becomes:

scanf("%d", &n);

And after correcting it worked normally, except for the fact that the binary is backwards.

Hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.