-2

我有以下代码段,在编译时会发出警告(代码仍然有效):

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

firsts、lasts、streets 和 zips 声明为:

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

我究竟做错了什么?

4

2 回答 2

3

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

当您分配 achar *的值时会发生这种情况const char *

于 2013-06-13T13:16:56.643 回答
1

firsts, lasts,streets 是数组,因此firsts[rand() % firsts_count];在您的情况下,like 操作将返回一个 const char* 值。

但是您正试图在 x_first_name 和 x_last_name 变量中收集这些值,这些变量是char*(指向 char 的指针)。所以在赋值时它失去了它的 const 特性。

于 2013-06-13T13:18:29.350 回答