1

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]
1''
  • 26,823
  • 32
  • 143
  • 200
user2680683
  • 13
  • 1
  • 3

1 Answers1

7

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

1''
  • 26,823
  • 32
  • 143
  • 200
  • 1
    +1 for the remarks about casts hiding errors. In general, casts are wrong. There are a few exceptions to this rule, but unless you really understand the reason for a cast being present, chances are it's masking a bug. – R.. GitHub STOP HELPING ICE Aug 14 '13 at 02:28