【发布时间】:2021-08-22 00:31:17
【问题描述】:
我在尝试创建包含字符串的可变大小数组时遇到问题。我试图创建一个多维数组,但这太难了。示例:
char *audio_types[8][40]; // 8 is number of string elements in the array by default; 40 is the maximum length of a string
audio_types = (char *) malloc(15); // increasing number of strings in the array
free(audio_types);
此外,我试图创建可变大小的指针数组。示例:
char *audio_types[40]; // 40 is the maximum length of a string
*audio_types = (char *) malloc(8); // setting number of strings to 8
free(audio_types);
问题是我不知道如何正确创建具有可变数量的字符串元素的数组。抱歉,我是 C 编程新手。简而言之,我的代码必须在一个数组中保存多个字符串元素。示例:
audio_types[0] // some string...
audio_types[1] // another string...
audio_types[2] // more another sting... etc.
希望您能理解我要问的问题。感谢您的关注。
【问题讨论】:
-
char* audio_types[40];声明了一个“40 (char*) 的数组”。与char[40]* audio_types比较,它是“指向 (char[40]) 的指针”。通常,它会简单地写成char** audio_types,接受数组衰减为“指向字符指针的指针(即指向字符串的指针)”。 -
malloc(15);分配 15 个字节。如果你想要 15 个指针audio_types = malloc(15 * sizeof(char *));并且不要强制转换 malloc 的返回值:stackoverflow.com/questions/605845/… -
如果你分配一个固定大小的数组,你不能改变它。因此,请从一开始就使用 malloc,然后调用 realloc 来更改大小。
-
char *audio_types[8][40];是一个由 320 个字符指针组成的二维数组。您要写的是char *audio_types[8];,它是8 个字符指针。这里不需要 40,因为数组中的指针还没有指向任何地方 - 当你创建指针指向的字符串时使用 40。 -
而
*audio_types = (char *) malloc(8);不起作用,因为*audio_types是一个字符而不是指针,并且您将一个8 字节字符数组分配给单个字符。您的编译器可能会打印一条警告,表明您正在做一些非法的事情。你可能想要audio_types = malloc(8 * sizeof(char *));
标签: arrays c string variables multidimensional-array