二维字符数组的动态内存 [英] dynamic memory for 2D char array
本文介绍了二维字符数组的动态内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我宣布一个数组
焦炭** ARR;
如何初始化二维字符数组的内存。
I have declared an array char **arr; How to initialize the memory for the 2D char array.
推荐答案
一种方法是做到以下几点:
One way is to do the following:
char **arr = (char**) calloc(num_elements, sizeof(char*));
for ( i = 0; i < num_elements; i++ )
{
arr[i] = (char*) calloc(num_elements_sub, sizeof(char));
}
这是相当清楚这里发生了什么 - 首先,你初始化数组的指针,那么这个数组你分配一个字符数组中的每个指针
It's fairly clear what's happening here - firstly, you are initialising an array of pointers, then for each pointer in this array you are allocating an array of characters.
您可以在一个功能包装这件事。你需要释放()他们来说,使用后,像这样的:
You could wrap this up in a function. You'll need to free() them too, after usage, like this:
for ( i = 0; i < num_elements; i++ )
{
free(arr[i]);
}
free(arr);
我觉得这个做的事情和最简单的方式匹配你所需要的。
I think this the easiest way to do things and matches what you need.
这篇关于二维字符数组的动态内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文