c - 如何从字符串初始化 char 数组

标签 c

我想做以下事情

char a[] = { 'A', 'B', 'C', 'D'};

但是我不想把这些字符分开写。我想要类似的东西

#define S "ABCD"

char a[] = { S[0], S[1], S[2], S[3] };

但这不会编译(gcc 说“初始化元素不是常量”)。

我尝试将#define 行替换为

const char S[] = "ABCD";

但这似乎没有帮助。

我怎样才能做到这一点(或类似的事情)让我把“ABCD”写成一个普通的“字符串”,而不是四个单独的字符?

附言似乎人们没有正确阅读问题......

我无法编译以下代码:

const char S[] = "ABCD";
char t[] = { S[0], S[1], S[2], S[3] };
char u[] = { S[3], S[2], S[1], S[0] };

最佳答案

你不能 - 在 C 中。在 C 中,全局和局部静态变量的初始化被设计成编译器可以将值静态地放入可执行文件中。它不能将非常量表达式作为初始值设定项处理。并且仅在 C99 中,您可以在聚合初始值设定项中使用非常量表达式 - 在 C89 中不是这样!

在您的情况下,由于您的数组是包含字符的数组,因此每个元素都必须是算术常量表达式。看看它是怎么说的

An arithmetic constant expression shall have arithmetic type and shall only have operands that are integer constants, floating constants, enumeration constants, character constants, and sizeof expressions.

你的初始化器肯定不满足这一点,它使用指针类型的操作数。当然,另一种方法是使用字符串文字初始化数组,正如它所解释的那样

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

所有引文均摘自 C99 TC3 委员会草案。所以总而言之,你想做的事情——使用非常量表达式——不能用 C 来完成。你有几个选择:

  • 多次写你的东西 - 一次颠倒,另一次不颠倒。
  • 改变语言 - C++ 可以做到这一切。
  • 如果您真的想做那些事情,请改用 char const* 数组

这是最后一个选项的意思

char const c[] = "ABCD";
char const *f[] = { &c[0], &c[1], &c[2], &c[3] };
char const *g[] = { &c[3], &c[2], &c[1], &c[0] };

这很好,因为地址常量表达式用于初始化指针

An address constant is a null pointer, a pointer to an lvalue designating an object of static storage duration, or a pointer to a function designator; it shall be created explicitly using the unary & operator or an integer constant cast to pointer type, or implicitly by the use of an expression of array or function type. The array-subscript [] and member-access . and -> operators, the address & and indirection * unary operators, and pointer casts may be used in the creation of an address constant, but the value of an object shall not be accessed by use of these operators.

您可能会幸运地调整您的编译器选项 - 另一引述:

An implementation may accept other forms of constant expressions.

关于c - 如何从字符串初始化 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/963911/

相关文章:

C++:如何使用名称长度从内存中的字符指针中取消引用多个字符

c - 获取两个 double 组的绝对差之和的有效方法

c - 在 C 中解析文件以读取字符

c - 在 c 中编写一个具有连接持久性支持的 http 服务器

c - 最后如何完善C语言的hangman循环问题?

c - 从文件中读取;无法创建进程

c - 就地从字符串中去除空格?

c - 将包含目录添加到 gcc *before* -I

c - 每个线程组的 Pthread 互斥量

c - makefile 编译不正确