c - 使用malloc分配不同行长的多维数组

标签 c arrays malloc

我有以下 C 代码:

int *a;
size_t size = 2000*sizeof(int);
a = malloc(size);

效果很好。但是如果我有以下内容:

char **b = malloc(2000*sizeof *b);

b 的每个元素都有不同的长度。

如何为 b 做与我为 a 做的相同的事情?即以下代码是否正确?

char *c;
size_t size = 2000*sizeof(char *);
c = malloc(size);

最佳答案

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


/* 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),您可以在一次分配中执行此操作。

关于c - 使用malloc分配不同行长的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1970698/

相关文章:

c - 为什么需要 DLL 才能使用 sqlite3?

c - Excel 加载项 : Assignment in for loop causes segmentation fault but line-by-line assignments work. 为什么?

c - getchar() 函数未读取正确的值

python - Linux 阻塞信号到 Python init

arrays - 如何使用 Jolt 将 n 个对象的 json 数组展平?

c - 为什么不在这种情况下使用 free()

c - C中最严格的类型是什么意思?

PHP array_merge_recursive 不能按我的意愿工作

asp.net-mvc - Asp.Net MVC 中数据库中的图像

c - 结构内的动态内存