简体   繁体   中英

C scanf format string warning

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);

使用%lu格式,因为它表示unsigned long int而不是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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM