简体   繁体   English

警告在初始化C字符串数组时从字符串const转换为char *

[英]Warning converting from string const to char* in initializing array of C strings

I used to do the following to declare and initialize an array of string in C: 我曾经做以下工作来声明和初始化C中的字符串数组:

char *myTable[] = {
   "ABC",  "Y", "*",  "*",
   "WXYZ", "Y", "*",  "*",
   "MNO",  "Y", "*",  "*",
   NULL,   NULL,NULL, NULL
};

The NULL's are for internal use. NULL供内部使用。

Since I moved to gcc 4.4.6, I get a warning: 由于我移至gcc 4.4.6,因此收到警告:

abc.cpp:74: warning: deprecated conversion from string constant to ‘char*’

What is the correct way of initializing my array ? 初始化数组的正确方法是什么?

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] 这是因为您正试图放弃这些字符串文字的常量性,并且编译器会考虑周全地警告您,因为尝试修改存储这些常量字符串文字的内存会导致未定义的行为 [1]

Declare your array as const char *myTable[] 将数组声明为const char *myTable[]


[1]: C99 Standard: 6.7.8 Initialization §32 : [1]: C99标准:6.7.8初始化§32

the declaration char *p = "abc"; 声明char *p = "abc"; defines p with type ''pointer to char '' and initializes it to point to an object with type ''array of char '' with length 4 whose elements are initialized with a character string literal. 用类型为“ pointer to char ”的指针定义p ,并将其初始化为指向长度为4的“ char型数组”类型的对象,该对象的元素使用字符串文字进行初始化。 If an attempt is made to use p to modify the contents of the array, the behavior is undefined. 如果试图使用p来修改数组的内容,则该行为是不确定的。

尝试使用const char *而不是char*

这是因为字符串文字是常量,所以您必须使用const char *myTable[]

a string that looks like "hello world" is an immutable string constant. 看起来像“ hello world”的字符串是一个不变的字符串常量。 You must declare 您必须声明

const char *myTable[] = {
   "ABC",  "Y", "*",  "*",
   "WXYZ", "Y", "*",  "*",
   "MNO",  "Y", "*",  "*",
   NULL,   NULL,NULL, NULL
}; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM