注意从字符串常量转换为char *初始化C字符串数组 [英] Warning converting from string const to char* in initializing array of C strings
问题描述
我以前做以下声明和初始化字符串的C中的数组:
I used to do the following to declare and initialize an array of string in C:
char *myTable[] = {
"ABC", "Y", "*", "*",
"WXYZ", "Y", "*", "*",
"MNO", "Y", "*", "*",
NULL, NULL,NULL, NULL
};
空的供内部使用。
The NULL's are for internal use.
自从我搬到与gcc 4.4.6,我得到一个警告:
Since I moved to gcc 4.4.6, I get a warning:
abc.cpp:74: warning: deprecated conversion from string constant to ‘char*’
什么是我的初始化数组的正确方法?
What is the correct way of initializing my array ?
推荐答案
这是因为你试图下车这些字符串的常量性和编译器足够体贴地提醒你一下,因为试图修改内存中,这些常量字符串存储导致的未定义行为 [1]
It's because you're trying to drop off the constness of these string literals and compiler is considerate enough to warn you about it since trying to modify the memory where these constant string literals are stored leads to undefined behaviour [1]
您声明数组作为为const char * myTable的[]
[1]: C99标准:6.7.8初始化§32
声明的char * p =ABC;
定义 P
类型'指针字符
''并初始化它指向同类型的对象'长度为4的元素都被初始化字符
''用字符串文字。 如果试图使用 P
修改数组中的内容,该行为是不确定的。
the declaration
char *p = "abc";
definesp
with type ‘‘pointer tochar
’’ and initializes it to point to an object with type ‘‘array ofchar
’’ with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
这篇关于注意从字符串常量转换为char *初始化C字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!