【问题标题】:Why does this code output the first element in the initializer?为什么这段代码会输出初始化程序中的第一个元素?
【发布时间】:2016-04-19 21:46:24
【问题描述】:

我的一个朋友今天给我发了这个代码:

#include <stdio.h>

int main()
{
    char *s = { "one", "two", "three", "four", "five" };
    puts(s);
}

它的输出是:

one

据我所知,"one" 之类的字符串在 C 中被翻译为地址,即常量。因此,"one", "two", "three", "four", "five" 等于 "five",因为其中有逗号运算符。那么{ "one", "two", "three", "four", "five" }不应该等于{ "five" },创建char *s="five"吗?

【问题讨论】:

  • 你真的想要char *s而不是char *s[]吗?
  • MSVC 说错误 C2078:初始化程序太多。所以代码无法输出one
  • 初始化列表中的逗号不是逗号操作符。他们只是分隔字段。但是您可以通过将表达式括在括号中来获取逗号运算符:char *s = { ("one", "two", "three") };(并且您会收到警告,左侧的 void 表达式没有任何效果。)

标签: c initialization initializer-list initializer


【解决方案1】:

此代码中的任何地方都没有逗号运算符。相反,逗号是初始化列表中的分隔符。

编译器会将char指针初始化为列表中的第一个字面量,并发出类似“excess elements in initializer”的警告,表示列表中剩余的元素已被丢弃。

正如 cmets 中已经提到的,你朋友的意图可能是

char *s[] = { "one", "two", "three", "four", "five" }

给 s[0]="one", s[1]="two" 等等。

【讨论】:

  • 但是当您更改 puts(s) 会导致编译器警告并打印垃圾信息。
  • 是的,因为 s 现在指向一个 char 指针数组,而 s[0]、s[1] 等指向字符串字面量。因此 puts(s) 将地址数据解释为字符串并打印垃圾,而 puts(s[0]) 将打印“one”。
猜你喜欢
  • 2023-02-17
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多