使用 malloc 分配不同行长的多维数组 [英] Using malloc for allocation of multi-dimensional arrays with different row lengths

查看:27
本文介绍了使用 malloc 分配不同行长的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 C 代码:

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);

其中 b 的每个元素都有不同的长度.

where every element of b has different length.

如何对 b 做和我对 a 做的一样的事情;即以下代码是否正确?

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);

推荐答案

首先,您需要像 char **c = malloc( N * sizeof( char* )) 一样分配指针数组,然后通过对 malloc 的单独调用分配每一行,可能在循环中:

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';

如果您知道元素的总数(例如 N*M),您可以在一次分配中完成此操作.

If you know the total number of elements (e.g. N*M) you can do this in a single allocation.

这篇关于使用 malloc 分配不同行长的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆