dotslash dotslash - 3 months ago 15
C Question

Cast warning when working with structures

I'm revisiting C after a long time and am puzzled by a warning generated by the compiler. Here's the relevant code:

struct Unit
{
char str1[100];
char str2[100];
short expected;
};

int main()
{
struct Unit arr[] =
{
{NULL, NULL, 0},
{NULL, "string", -1},
{"string", NULL, 1},
{"string", "string", 0},
{"string1", "string2", -1},
{"string2", "string1", 1},
{"str", "string", -1},
{"string", "str", 1}
};

printf("%d\n", arr[0].expected);
return 0;
}


When compiled, I get:

my_strcmp.c: In function ‘main’:
my_strcmp.c:64:9: warning: initialization makes integer from pointer without a cast [enabled by default]
{NULL, NULL, 0},
^
my_strcmp.c:64:9: warning: (near initialization for ‘arr[0].str1[0]’) [enabled by default]
my_strcmp.c:64:9: warning: initialization makes integer from pointer without a cast [enabled by default]
my_strcmp.c:64:9: warning: (near initialization for ‘arr[0].str1[1]’) [enabled by default]
my_strcmp.c:65:9: warning: initialization makes integer from pointer without a cast [enabled by default]
{NULL, "string", -1},
^
my_strcmp.c:65:9: warning: (near initialization for ‘arr[1].str1[0]’) [enabled by default]
my_strcmp.c:65:9: warning: initialization makes integer from pointer without a cast [enabled by default]
my_strcmp.c:65:9: warning: (near initialization for ‘arr[1].str1[1]’) [enabled by default]
my_strcmp.c:66:9: warning: initialization makes integer from pointer without a cast [enabled by default]
{"string", NULL, 1},
^
my_strcmp.c:66:9: warning: (near initialization for ‘arr[2].str2[0]’) [enabled by default]


I don't get it; where am I making integer from pointer? Please help.

Answer

I am assuming that line 64, 65 and 66 are the ones where you initialize the structure using NULL. That will not work because NULL is a pointer, and you can't initialize an array with a pointer.

The only solution I can see is to either turn the string arrays in the structure to pointers, or to initialize the "unused" strings to the empty string "".