解引用指针数组

时间:2019-05-20 04:38:07

标签: c pointers

在处理这个简单的取消引用语句时,我遇到了麻烦。

我尝试打印**names,然后得到*names -- 'C'的期望值。但是,*names给了我'D'

#include <stdio.h>


int main(void)
{
   char *names[] = {"Carl", "David", "Gibson", "Long", "Paul"};
   printf("%c\n", *names);

   return 0;
}

控制台将打印出'D'。我不确定为什么char产生的*names不是第一项'C'的首字母。

2 个答案:

答案 0 :(得分:3)

这是未定义的行为,输出随编译器而变化。
当我用gcc运行它时,没有输出。使用**names打印'C'。
未定义的行为是由于格式说明符错误。您使用%c,但是*names指向数组中的第一个元素,即存储“ Carl”的char数组。
使用%s格式说明符来打印字符串。

printf("%c\n", *names);

答案 1 :(得分:3)

编译此代码时,GCC将为您提供以下内容:

test.c:5:12: warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]
   printf("%c\n", *names);
           ~^     ~~~~~~
           %s

因此,您基本上是在尝试打印名字的第一个字符,但是您没有传递char作为参数,而是传递了一个指向char的指针。您可以做的是这样:

printf("%c\n", *names[0]);

,其中您指定要从第一个元素中获取第一个字符。

此外,使用**names与使用*names[0]