我想弄清楚如何创建一个字符串数组(考虑到我知道每个字符串的最大长度)。
char** strings = NULL;
strings = malloc (5*sizeof(char*));
一旦我这样做了,我怎么能只填充数组而不需要单独分配每个字符串?假设我知道字符串的最大长度是 20,我该如何设置?
分配字符串后,我希望执行以下操作:
strings[0] = "string";
strings[1] = "another string";
等等。
谢谢
您可以声明一个指向的指针数组,char
然后将字符串文字分配给这些指针
char *strings[5];
strings[0] = "string";
strings[1] = "another string";
/* ... */
但请注意,这些字符串将是不可变的。
您还可以使用数组char
数组
char strings[5][20]; // As you know max length of string is 20
strcpy(strings[0], "string");
strcpy(strings[1], "another string");
/* ... */
后者的优点之一是字符串是可变的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句