C(Linux):警告:赋值从指针目标类型中丢弃限定符

时间:2013-06-13 13:06:40

标签: c

我有以下代码片段在编译时给出了警告(代码仍可正常工作):

char *x_first_name, *x_last_name, *x_address, *x_zip;

const size_t firsts_count = sizeof(firsts) / sizeof(firsts[0]);
const size_t lasts_count = sizeof(lasts) / sizeof(lasts[0]);
const size_t streets_count = sizeof(streets) / sizeof(streets[0]);
const size_t zips_count = sizeof(zips) / sizeof(zips[0]);

srand(time(NULL));

x_first_name = firsts[rand() % firsts_count]; // line 69
x_last_name = lasts[rand() % lasts_count]; // line 70
x_address = streets[rand() % streets_count]; // line 71
x_zip = zips[rand() % zips_count]; // line 72

警告编译:

authorize.c: In function 'main':
authorize.c:69: warning: assignment discards qualifiers from pointer target type
authorize.c:70: warning: assignment discards qualifiers from pointer target type
authorize.c:71: warning: assignment discards qualifiers from pointer target type
authorize.c:72: warning: assignment discards qualifiers from pointer target type
第一,持续,街道和拉链被宣布为:

const char *firsts[] = {
        "Asgar",
        "Aadit",
        "Aanand",
        "Aaron"
};

我做错了什么?

2 个答案:

答案 0 :(得分:3)

正如编译器所述,你在分配时从指针中丢弃限定符(在这种情况下为const)。

当您为char *分配const char *时会发生这种情况。

答案 1 :(得分:1)

第一,持续,街道是数组,所以像firsts[rand() % firsts_count];这样的操作将返回一个值为const char *的情况。

但是你试图在x_first_name和x_last_name变量中收集这些值,这些变量是char*(指向char的指针).so在赋值时它会失去它的const性质。