warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

user2680683 picture user2680683 · Aug 14, 2013 · Viewed 7.4k times · Source

I was learning C with a book called "C in Linux" by David Haskins but there's a problem. When i try to compile this code:

#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; 
}

The terminal shows this warning!

chapter4_1.c: In function ‘main’:
chapter4_1.c:14:16: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

Answer

1&#39;&#39; picture 1'' · Aug 14, 2013

You forgot to #include <stdlib.h>. This means that getenv() isn't declared anywhere, so it's assumed to return an int by default, which you're casting to char *. On a 64-bit machine, int (32 bits) and char * (64 bits) have different sizes, hence the warning.

As an aside, the cast to char * is not necessary, since getenv() already returns a char *. The cast only serves to mask errors (i.e. without it, the program would have given you a clear error message about passing an int to a char *).