警告:从不同大小的整数转换为指针[-Wint-to-pointer-cast]

1 c warnings compiler-errors strncpy getenv

我正在用David Haskins的一本名为"C in Linux"的书学习C,但是有一个问题.当我尝试编译此代码时:

#include <stdio.h>
#include <string.h>

int main (int argc, char *argv[], char *env[]) {

    printf("Content-type:text/html\n\n<html><body bgcolor=#23abe2>\n"); 
    char value[256] = "";

    strncpy(value,(char *) getenv("QUERY_STRING"), 255);
    printf("QUERY_STRING:%s<BR>\n", value );
    printf("<form>\n");
    printf("<input type=\"TEXT\" name=\"ITEM1\"> \n");
    printf("<input type=\"TEXT\" name=\"ITEM2\"> \n");
    printf("<input type=\"SUBMIT\">");
    printf("</form></body></html>\n");

    return 0; 
}
Run Code Online (Sandbox Code Playgroud)

终端显示此警告!

chapter4_1.c: In function ‘main’:
chapter4_1.c:14:16: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
Run Code Online (Sandbox Code Playgroud)

1''*_*1'' 7

你忘了#include <stdlib.h>.这意味着getenv()没有在任何地方声明,所以假设它int默认返回一个你要投射到的char *.在64位机器上,int(32位)和char *(64位)具有不同的大小,因此警告.

顺便说一句,演员char *是没有必要的,因为getenv()已经返回了char *.演员只是为了掩盖错误(即没有它,程序就会给你关于传递一个明确的错误消息intchar *).