-2

I know other versions of this questions exist, but all of the answers for them confuse my beginner brain. All I am trying to do is take a single number as input and then output it, here is the code:

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


int main() {
        int var;

        scanf("%u\n", var);
        printf("%d\n", var);
}

and the error message I got:

warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 2 has type ‘int’ [-Wformat=]

The weird thing is that I tried all the format specifiers for integers that I could think of (%d %u %i) and they all returned a similar error.

I'm still a beginner in C so this might be a really stupid question but go easy on me lol

1 Answers1

1

scanf needs to be able to write into var. Currently, you're only passing it a copy of the value of var, but that's of no use to it.

Instead, you need to pass in a pointer to var, so that it can write into that pointer's location:

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


int main() {
    int var;

    scanf("%d", &var);
    printf("%d\n", var);
}
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • ah alright im doing the w3schools tutorial rn and i havent gotten to pointers yet, ig i should have waited before trying this myself lol – Mr_Arsonist Feb 17 '22 at 02:33
  • It's a bit of a boogyman topic IMO. It's really not so scary. You're just passing the location of a value, rather than a value itself. You're familiar with this in daily life. When you want someone to call you, you give them your phone number, and not your phone. When you want to receive mail, you give some one your address, not your house. – Alexander Feb 17 '22 at 02:36
  • thats a good explanation one thing im confused about though is why i dont have to use & with strings, on the tutorial im looking at they leave it out-: `// Create a string` `char firstName[30];` `// Ask the user to input some text` `printf("Enter your first name: \n");` `// Get and save the text` `scanf("%s", firstName);` `// Output the text` `printf("Hello %s.", firstName);` – Mr_Arsonist Feb 17 '22 at 02:45
  • oops nevermind my last comment- i ended up figuring it out – Mr_Arsonist Feb 17 '22 at 02:55
  • @Mr_Arsonist there is nothing special about pointers. A few links that provide basic discussions of pointers may help. [Difference between char *pp and (char*) p?](https://stackoverflow.com/a/60519053/3422102) and [Pointer to pointer of structs indexing out of bounds(?)...](https://stackoverflow.com/a/60639540/3422102) (ignore the titles, the answers discuss pointer basics) – David C. Rankin Feb 17 '22 at 03:38