使用malloc与不同的行长度多维数组分配 [英] Using malloc for allocation of multi-dimensional arrays with different row lengths
问题描述
我有如下的 C
code:
为int *一个;
为size_t大小= 2000 * sizeof的(INT);
A =(INT *)malloc的(大小);
这工作正常。但是,如果我有以下几点:
的char ** B =的malloc(2000 * sizeof的* B);
其中,b 的每一个元素都有不同的长度。
这怎么可能做到为同样的事情b
为我做了 A
;即以下code将举行是否正确?
的char * C;
为size_t大小= 2000 * sizeof的(字符*);
C =(字符*)malloc的(大小);
首先,你需要分配的指针数组像的char ** C =的malloc(N * sizeof的(字符*))
,然后用一个单独调用分配每行的malloc
,大概在循环:
/ * N是行数* /
/ *注意:C为char ** * /
如果((C =的malloc(N * sizeof的(字符*)))== NULL)
{/ *错误* /}对于(i = 0; I< N;我++)
{
/ *这里x_i是给定行的大小,没有必要
*乘的sizeof(char)的,它总是1
* /
如果((C [i] =的malloc(x_i))== NULL)
{/ *错误* /} / *这里大概初始化的行* /
}/ *访问矩阵元素:C [I]给你一个指针
*对排阵,C [i] [j]的索引元素
* /
C [I] [J] ='A';
如果您知道的元素总数(例如 N * M
),您可以在一个单一的分配做到这一点。
I have the following C
code :
int *a;
size_t size = 2000*sizeof(int);
a = (int *) malloc(size);
which works fine. But if I have the following :
char **b = malloc(2000*sizeof *b);
where every element of b
has different length.
How is it possible to do the same thing for b
as i did for a
; i.e. the following code would hold correct?
char *c;
size_t size = 2000*sizeof(char *);
c = (char *) malloc(size);
First, you need to allocate array of pointers like char **c = malloc( N * sizeof( char* ))
, then allocate each row with a separate call to malloc
, probably in the loop:
/* N is the number of rows */
/* note: c is char** */
if (( c = malloc( N*sizeof( char* ))) == NULL )
{ /* error */ }
for ( i = 0; i < N; i++ )
{
/* x_i here is the size of given row, no need to
* multiply by sizeof( char ), it's always 1
*/
if (( c[i] = malloc( x_i )) == NULL )
{ /* error */ }
/* probably init the row here */
}
/* access matrix elements: c[i] give you a pointer
* to the row array, c[i][j] indexes an element
*/
c[i][j] = 'a';
If you know the total number of elements (e.g. N*M
) you can do this in a single allocation.
这篇关于使用malloc与不同的行长度多维数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!