codingbonobo
codingbonobo

Reputation: 23

Variable in C program behaving weirdly in Visual studio

I created a test project with the following code to check for problem:

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

    int main(void) {
    int a;
    scanf_s("%d", &a);
    printf("%d", &a);
}

I enter the input of 1 and it gives me random numbers of 7 digits like this

and this

can someone help please

Upvotes: 1

Views: 82

Answers (2)

Serdalis
Serdalis

Reputation: 10489

You're printing out the value of the memory address to a, not the value of what the variable a is holding.

You'll want to use the variable directly like:

printf("%d", a);

to print the actual value of a.

The CPP reference wiki also contains good information for C functions if you want to see how they should be used.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 882206

The scanf family of functions needs addresses because it writes to those addresses to populate the variables.

Since the printf family only needs the values (although, for C strings, that's the same thing), you should get rid of the & operator:

printf("%d", a);

Otherwise you're trying to print out the address of that variable rather than the value.

Upvotes: 4

Related Questions