Question

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]
Was it helpful?

Solution

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 *).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top