Ansh Ansh - 5 months ago 41
C Question

Scanf_s reading wrong input

For this code below (in C)

int small_a, small_b;
printf("Please input two numbers\n");
scanf_s("%d %d", &small_a, &small_b);
printf("%d %d", &small_a, &small_b);
int test_2nd = small_a - small_b;
if (test_2nd < 0) {
printf("a is smaller %d", &small_a);
else {
printf("b is smaller %d", &small_b);

The values it prints when I write 4 and 2 is a huge six digit number (5504620 and 5504608 in this case) I don't understand where it goes wrong.
has been included as a header.


The problem here is in the print statement. In the code

 printf("%d %d", &small_a, &small_b);

you don't need (want) to take (print) the address. Remove that &.

That said, this actually invokes undefined behavior. %d with printf() expects an argument of type int and you're essentially supplying an int *, causing the UB.

FWIW, to print an address (pointer), you need to use %p format specifier and cast the argument to void *