C scanf format string warning
-
14-03-2021 - |
Вопрос
I'm working on Euler #3 (http://projecteuler.net/problem=3). I think I've got the logic right, but I'm getting an error when trying to use scanf (and printf) with a long. I'm current trying to use %li and this is the error I'm getting:
euler3.c: In function ‘main’:
euler3.c:30: warning: format ‘%li’ expects type ‘long int **’, but argument 2 has type ‘long int’
euler3.c:30: warning: format ‘%li’ expects type ‘long int *’, but argument 2 has type ‘long int’
I understand the error, but for the life of me I can't find the solution. Here's my code if it's needed.
#include <stdio.h>
long greatestPrime(long num)
{
int i;
for(i = 2; i <= num; i++)
{
if(num%i == 0)
{
num = num/i;
i--;
}
}
return num;
}
int main(int argc, char *argv[])
{
unsigned long greatest;
printf("Enter number to find prime factor: ");
scanf("%li",greatest);
printf("%li",greatestPrime(greatest));
return 0;
}
Решение
scanf
is looking for a pointer to a long integer (long int *
), not a long integer, so you need to pass the address of greatest
by using the &
operator:
scanf("%li", &greatest);
As another answer shows as well, you need to use %lu
, as you're using an unsigned long int
:
scanf("%lu", &greatest);
Другие советы
Use %lu
format, as it represents an unsigned long int
instead of just a long int
scanf("%lu",&greatest);
In order for scanf
to modify your variable, it needs the address of it (a pointer to your variable). Pass the address of greatest
using the &
operator:
scanf("%lu", &greatest);
EDIT: Also, %li
should be %lu
, since greatest
is unsigned.
You're passing an integer to scanf()
:
scanf("%li",greatest);
You should be passing the address of a variable properly typed to hold an unsigned long integer:
scanf("%lu", &greatest);