C-指向不起作用的字符串数组的指针

时间:2018-08-18 10:36:38

标签: c arrays string pointers

我正在尝试使指针指向要迭代的字符串数组。 我有这样定义的数组:

const char **Argument_ACTIONS={
"default",
"store_true",
"store_false",
"show_help",
"show_version",
NULL
};

在函数中我有那段代码:

char **ptr=&Argument_ACTIONS;
printf("%s\n",*ptr);
ptr++;
printf("%s\n",*ptr);

预期输出为:

  

默认

     

store_true

但是我得到了:

  

默认

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的数组定义不正确,应该是:

const char *Argument_ACTIONS[] = { // <-- notice [] which defines an array
    "default",
    "store_true",
    "store_false",
    "show_help",
    "show_version",
    NULL
};

在您的情况下,您定义了一个双指针并为其分配了一个单指针列表。这实际上没有意义,但是C编译器允许它带有一些警告。实际上,它会将第一个字符串从const char *隐式转换为const char **并丢弃其余的字符串:

main.c:2:1: warning: initialization of ‘const char **’ from incompatible pointer type ‘char *’ [-Wincompatible-pointer-types]
 "default",
 ^~~~~~~~~
main.c:2:1: note: (near initialization for ‘Argument_ACTIONS’)
main.c:3:1: warning: excess elements in scalar initializer
 "store_true",
 ^~~~~~~~~~~~
main.c:3:1: note: (near initialization for ‘Argument_ACTIONS’)
main.c:4:1: warning: excess elements in scalar initializer
 "store_false",
 ^~~~~~~~~~~~~
main.c:4:1: note: (near initialization for ‘Argument_ACTIONS’)
main.c:5:1: warning: excess elements in scalar initializer
 "show_help",
 ^~~~~~~~~~~
main.c:5:1: note: (near initialization for ‘Argument_ACTIONS’)
main.c:6:1: warning: excess elements in scalar initializer
 "show_version",
 ^~~~~~~~~~~~~~
main.c:6:1: note: (near initialization for ‘Argument_ACTIONS’)

您应将ptr更改为:

const char **ptr = Argument_ACTIONS;