c - 如何使用 malloc 在 C 中创建动态字符串数组

标签 c arrays malloc realloc

当没有固定长度的项目或字符时,如何创建字符串数组。一般来说,我是指针和 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/

相关文章:

c - 要么你真的不能像这样传递数组的一部分..要么有些东西很奇怪

linux - 如何在64位系统上强制malloc返回32位(如指针)?

c - 在 c 中取消分配结构?

c - malloc 和 calloc 在使用上的区别

python - Numpy 数组 : group by one column, 求和另一个

c - libxml2:xmlNewTextWriterFilename 泄漏

c - 为什么此C程序编译时没有错误?

c++ - 调用函数传递数组

arrays - 如何替换 PostgreSQL 中文本列中的字符数组?

ruby-on-rails - 在字符串 rails 中提取数组