当没有固定长度的项目或字符时,如何创建字符串数组。一般来说,我是指针和 c 的新手,我无法理解此处发布的其他解决方案,因此我的解决方案发布在下面。希望它能帮助其他人。
最佳答案
char **twod_array = NULL;
void allocate_2darray(char ***source, int number_of_slots, int length_of_each_slot)
{
int i = 0;
source = malloc(sizeof(char *) * number_of_slots);
if(source == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);}
for(i = 0; i < no_of_slots; i++){
source[i] = malloc(sizeof(char) * length_of_each_slot);
if(source[i] == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);}
}
}
//示例程序
int main(void) {
allocate_2darray(&twod_array, 10, 250); /*allocate 10 arrays of 250 characters each*/
return 0;
}
关于c - 如何使用 malloc 在 C 中创建动态字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13109008/