简体   繁体   中英

Why this is "assignment to ‘char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]"

Recently I study C and there is what I can't understand.
I knew and found that gets( ) function returns char * .

char * gets(char *buffer)

#include <stdio.h>

int main(void)
{
    char str[20], *p;
    p = gets(str) /* <- gcc said warning: assignment ~. */
}

definitely p is char * type and the return type of gets( ) is also char * .
Then why gcc said warning:

assignment to 'char *' from 'int' makes pointer from integer without a cast [-Wint-conversion]?

Well it's working... but I just expected compiling with no any messages.

Edit:

  1. char * gets(char *buffer) was exist but now removed from language.

  2. But it is still in library.

  3. Then,with implicit declaration, gets is compiled with default return value int .

  4. Though gets works well, It's very dangerous to use. Now fgets much better choice than gets

In addtion, I wanna know that how gets is exist on header file.

#if __CLIBC_USE (DEPRECATED_GETS)
/* Get a newline-terminated string from stdin, removing the newline.

This function is impossible to use safely. It has been officially removed from ISO c11 and ISO c++14, and we have also removed it from the _GNU_SOURCE feature list. It remains available when explicitly using an old ISO C, Unix, or POSIX standard.

This function is a possible cancellation point and therefore not marked with __THROW. */
extern char *gets (char *__s) __wur __attribute_deprecated__;
#endif

I could understand #ifdef that comments told me and how function is declared to be used.

Thank you for everyone! (_ _ )

You certainly got another warning warning: implicit declaration of function 'gets'; .

That means that the compiler didn't find the definition of gets (presumably because it has been removed from the language about 10 years ago). Therefore it assumes that gets is a function that returns an int and p = gets(str) would then assign an int to a pointer, hence the second warning assignment to 'char *' from 'int' makes pointer from integer without a cast .

If you see warnings containing the word "implicit", consider them as an error.

And "makes pointer without a cast" warnings are almost always actually errors.

I suggest you use fgets instead, but be aware that with fgets your line ends usually with a \n (that can be removed easily, for more details read this: Removing trailing newline character from fgets() input )

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