在C中取消引用字符串文字会有什么影响?

时间:2012-12-16 04:10:00

标签: c

#include<stdio.h>

int main()
{
    printf("%c",*"abcde");
    return 0;
}

这个程序的输出怎么样? 让我知道为什么在使用turbo c编译时输出为'a',这里的'*'意味着什么?

2 个答案:

答案 0 :(得分:2)

"abcde"是一个字符串文字,是一个字符数组(char[])。 通常放置在程序的只读数据部分中。如果你要将它传递给printf,编译器实际上是将该数组的地址传递给printf

但是,在这里你取消引用那个只传递第一个字符的指针。

这是一个更有意义的等效,更详细的版本:

const char* str = "abcde";    // str is a char* pointer to "abcde"
char c = *str;                // De-reference that pointer - in other words,
                              //   get me the char that it points to.
printf("%c", c);              // Pass that char to printf, where %c is
                              //   expecting a char.

答案 1 :(得分:2)

"abcde"是一个字符串文字,因此具有数组类型。在sizeof&的操作数的任何上下文中,数组衰减到指向其第一个元素的指针。因此,当用作一元*运算符的操作数时,"abcde"被计算为指向字符串开头的“a”的指针,*运算符取消引用该指针,获得值'a'。将此值(整数)传递给printf以使用%c格式说明符进行格式化会导致printf将相应的字符“a”打印到stdout。

相关问题