[英]What is the best way to initialize a pointer to a char array as mutable?
It is clear that initializing a char array like 很明显,初始化一个char数组就像
char* string = "foobar";
will make it immutable. 会让它变得一成不变。 On the other hand, initializing a char array like 另一方面,初始化一个char数组
char string[] = "foobar";
will be make it mutable. 将使它变得可变。
What is the best way to make a mutable initialization of pointer to a char array? 对指向char数组的指针进行可变初始化的最佳方法是什么?
// member char arrays are immutable
char* arr[] = {"foo", "bar"};
假设您拥有C99功能,复合文字可以解决这个问题:
char *arr[] = { (char[]){"foo"}, (char[]){"bar"} };
One options is to guess the maximum size of the strings in the array, and use: 一种选择是猜测数组中字符串的最大大小,并使用:
char arr[][SIZE] = {"foo", "bar"};
where SIZE
is to be replaced by a number. 其中SIZE
将被一个数字替换。
char arr[][4] = {"foo", "bar"};
would work given the strings but it won't if you use: 如果您使用以下字符串将会工作:
char arr[][4] = {"foo", "fubar"};
When such a line is compiled, gcc prints the following warning: 编译这样的行时,gcc会输出以下警告:
warning: initializer-string for array of chars is too long [enabled by default] char arr[][4] = {"foo", "fubar"}; 警告:字符数组的初始化字符串太长[默认情况下启用] char arr [] [4] = {“foo”,“fubar”};
If you are using a different compiler, it might not complain. 如果您使用的是其他编译器,则可能不会抱怨。 Just be aware. 请注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.