数组元素在C字符串数组可变 [英] Array Element is a Variable in Array of Strings in C

查看:138
本文介绍了数组元素在C字符串数组可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在初始化字符串C.我想设置从变量数组的元素之一的数组,但我得到一个编译器错误。这有什么错呢?

I'm trying to initialize an array of strings in C. I want to set one of the elements of the array from a variable, but I'm getting a compiler error. What's wrong with this?

char * const APP_NAME = "test_app";

char * const array_of_strings[4] = {
    APP_NAME,
    "-f", "/path/to/file.txt",
    NULL
};

错误是错误:初始元素不是常数

推荐答案

标准的与众不同之常量 -qualified变量和编译时间常数。

The standard distinguishes const-qualified variables and compile time constants.

评估的变量( APP_NAME )不认为是一个编译时在C标准意义上的常数。这

Evaluating a variable (APP_NAME) is not considered to be a compile time constant in the sense of the C standard. This

char const app_name[] = "test_app";

char const*const array_of_strings[4] = {
    &app_name[0],
    "-f", "/path/to/file.txt",
    0,
};

将被允许的,因为这不是评估 APP_NAME 但只考虑它的地址。

此外,你总是应该把字符串文字,如果他们不得不输入字符常量[] 。修改他们已经未定义的行为,所以你应该保护自己这样做。

Also, you always should treat string literals as if they had type char const[]. Modifying them has undefined behavior, so you should protect yourself from doing so.

这篇关于数组元素在C字符串数组可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆