开发者社区> 问答> 正文

使用malloc分配具有不同行长的多维数组

我有以下C代码:

int a; size_t size = 2000sizeof(int); a = (int *) malloc(size); 效果很好。但是如果我有以下内容:

char **b = malloc(2000*sizeof *b); 其中的每个元素b都有不同的长度。

怎么可能做b和我一样的事情a;即下面的代码将保持正确?

char c; size_t size = 2000sizeof(char *); c = (char *) malloc(size); 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-09 11:45:12 404 0
1 条回答
写回答
取消 提交回答
  • 首先,您需要分配指针数组,例如char *c = malloc( N * sizeof( char )),然后malloc可能在循环中通过对的单独调用来分配每一行:

    /* N is the number of rows / / note: c is char** / if (( c = malloc( Nsizeof( 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'; 如果您知道元素的总数(例如NM),则可以一次分配。

    2020-02-09 11:45:22
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载