Using malloc for allocation of multi-dimensional a

2019-01-01 09:09发布

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

标签: c arrays malloc
8条回答
高级女魔头
2楼-- · 2019-01-01 09:29

I think a 2 step approach is best, because c 2-d arrays are just and array of arrays. The first step is to allocate a single array, then loop through it allocating arrays for each column as you go. This article gives good detail.

查看更多
柔情千种
3楼-- · 2019-01-01 09:36

malloc does not allocate on specific boundaries, so it must be assumed that it allocates on a byte boundary.

The returned pointer can then not be used if converted to any other type, since accessing that pointer will probably produce a memory access violation by the CPU, and the application will be immediately shut down.

查看更多
登录 后发表回答