使用结构时发出警告

时间:2016-08-13 07:14:50

标签: c

我在很长一段时间后重新访问C,并对编译器生成的警告感到困惑。这是相关代码:

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

编译时,我得到:

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]

我没有得到它;我在哪里用指针做整数?请帮忙。

1 个答案:

答案 0 :(得分:4)

我假设第64,65和66行是使用NULL初始化结构的行。这是行不通的,因为NULL是一个指针,你不能用指针初始化一个数组。

我能看到的唯一解决方案是将结构中的字符串数组转换为指针,或初始化"未使用的"字符串到空字符串""