简体   繁体   English

将指向char数组的指针初始化为可变的最佳方法是什么?

[英]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.

相关问题 初始化指向struct的指针数组的正确方法是什么? - What is the correct way to initialize an array of pointer to struct? 在c中初始化字符串数组的最佳方法是什么? - What is the best way to initialize the string array in c? 在C中,我可以在指针声明中初始化字符串,就像我可以在char数组声明中初始化字符串一样吗? - In C, can I initialize a string in a pointer declaration the same way I can initialize a string in a char array declaration? 在C中按一定比例随机初始化数组的最佳方法是什么? - What's the best way to randomly initialize an array in C, with certain proportions? 在C中初始化高维数组的最佳方法是什么? - What is the best way to initialize a high dimensional array in C? 声明和初始化动态分配的二维数组的最佳方法是什么? - What is the best way to declare and initialize a 2D array dynamically allocated? 如何使用C中的char指针初始化char数组 - How to initialize a char array using a char pointer in C 在C / C ++中清除char数组的最佳方法是什么? - What is the best way of clearing a char array in C/C++? 如果在char数组和char指针中未将内存分配给'\\ 0'怎么办 - What if memory is not allocated to '\0' in char array and char pointer 什么是无符号字符数组以及如何声明和初始化它 - what is unsigned char array and how to declare and initialize it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM