0

我有以下代码:

const char* names = {"apples", "oranges", "grapes"};

什么数据类型&name[0]?海湾合作委员会在抱怨。它不是 const char** 因为 GCC 抱怨这个:

const char** address_of_first_name = &name[0];

"note: expected 'const char ** ' but argument is of type 'char **' "

是常量char * const 还是什么?头痛进行中...

什么数据类型&name[0]?我不想错误地修复这个编译器错误。

4

3 回答 3

4

如果您创建names一个指针数组const char* names[]并像以前一样初始化它们,那么您可以执行以下操作:

#include <stdio.h>

int main()
{
   const char* names[] = {"apples", "oranges", "grapes"};

   const char* first = names[0];
   const char* second = names[1];
   const char* third = names[2];

   const char* foo = &(*names[0]);

   printf("%s", foo);
   printf("%s", second);
   printf("%s", third);

}

现场示例

如果你想要地址,你可以这样做:

 const char* addr = &(*names[0]); //print addr gets "apples"
 const char** add = &names[0]; //print add gets 0x7fff14531990
于 2013-04-03T07:42:52.187 回答
4

正确地,您的数组应该看起来像

const char* names[] = {"apples", "oranges", "grapes"}; // array of pointer to char

现在,当你申请

name[0];

这会将地址返回到第一个元素。(“苹果”)

而不是

const char** first_name = &name[0];

尝试

const char* first_name = name[0];

所以你得到了数组中的第一个字符串。

于 2013-04-03T07:45:14.237 回答
2

这个问题是有缺陷的,因为

const char* names = {"apples", "oranges", "grapes"};

const char*像数组一样初始化标量。

于 2013-04-03T07:42:59.663 回答