【发布时间】:2021-07-29 12:36:11
【问题描述】:
可以用字符串字面量初始化字符串
char word1[] = "abc";
或作为带有空终止符的 char 数组。
char word2[] = {'a', 'b', 'c', '\0'};
除了写word1[],word1也可以写成指针符号
char *word1 = "abc";
但是,当尝试使用指针表示法编写 word2 时
char *word2 = {'a', 'b', 'c', '\0'};
它向我显示了一堆警告,例如
警告:标量初始值设定项 char 中的多余元素 *word2 = {'a', 'b', 'c', '\0'};
当我运行程序时,我得到Segmentation fault (core dumped)。
这是为什么呢?为什么你可以写char *word = "abc" 而不能写char *word = {'a', 'b', 'c', '\0'}?
【问题讨论】:
-
试试compound literal:
char *word2 = (char[4]){'a', 'b', 'c', '\0'}; -
@pmg 非常感谢您的指点。复合文字对于我来说仍然有点太新奇了。我已经更新了我的答案。