1

I seriously don't know what is wrong. It may be something very simple, but I can't find the error. I wrote this very simple program in C:

#include<stdio.h>

int main(void) {

    int n;
    scanf("%d", &n);
    printf("\n%d", &n);

    return 0;
}

But when I ran it, this is what I got:

1  // My input

-1936471972

What am I doing wrong?

Thanks in advance!

4 Answers4

2

I'll just post what the others have already pointed out:

int main(void) {

    int n;
    scanf("%d", &n);
    printf("%d\n", n);
              ^^  ^ 
    return 0;
}

Remove the & from &n if you just want to display the value of the variable (you were basically printing the address of the variable) and move the \n after you have printed the variable as explained by Weather Vane.

Community
  • 1
  • 1
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
  • 3
    To enlarge on my above comment: the output through `stdout` is usually buffered, and that buffer is sent to the output device when a `newline` is sent. So if you are printing cues about the state of your program which lack the final `newline`, and your program crashes, the previous output may still be in the buffer, and not actually sent to the device. This can make the debugging cues misleading or useless. It's just good practice to put the `newline` last. But if there are circumstances when you do not *want* a `newline` you can use `fflush(stdout);` – Weather Vane Sep 24 '16 at 19:18
  • @Weather Vane Use `stdout()` for certainty. A `'\n'` [might not flush the output](http://stackoverflow.com/q/39536212/2410359). – chux - Reinstate Monica Sep 25 '16 at 02:10
1

I seriously don't know what is wrong.

printf("\n%d", &n); use a print specifier of "%d", which expects an int. &n is the address of an int. What is really good about this is the modern compilers and compilers with their warnings well enable, will automatically warn about this error. This saves you time! No need for an SO post.

Proficient coders uses tools like a compiler with is warnings well enabled to be efficient and focus on the subtle problems a compilers cannot detect. Using printf("\n%d", n); or printf("%d\n", n); may solve today's small problem, but using a better compiler environment is really the thing to learn from all this.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

Use that

printf("%d\n", n);

instead of

printf("\n%d", &n);
Marcel
  • 2,810
  • 2
  • 26
  • 46
0

scanf takes a variable address as a parameter, butprintf takes the variable value. Try changing the line to

printf("\n%d", n);
user1717828
  • 7,122
  • 8
  • 34
  • 59