Allocating 2-D array in C

我与影子孤独终老i 提交于 2020-01-21 14:56:08

问题


I want to allocate a 2-D array in C at runtime. Now this can be achieved in the conventional manner like this:

int *matrix[rows]
for (row = 0; row < rows; ++row) {
  matrix[row] = (int *)malloc(ncol*sizeof(int));
}

But I found another method, which does the same thing:

int (*p)[rows];
p=(int (*)[rows])malloc(rows*cols*sizeof(int));

Can anyone explain how the 2nd declaration works? Specifically, what is meant by (int (*)[rows])malloc? To the best of my knowledge, malloc is used like (int *)malloc(ncol*sizeof(int)) or (char *)malloc(ncol*sizeof(char)).


回答1:


Here, you cast malloc's return value to the type pointer to array rows of int.

By the way, in C, the cast of a pointer to void to a pointer to object is not requiered, and even useless. You should not worry about these details. The following code works indeed as well.

#include <stdlib.h>

int (*p)[rows];
p = malloc(rows * cols * sizeof(int));



回答2:


These are not equivalent, the first allocates an array of pointers to integers, the second allocates an array of integers and returns a pointer to it, you just allocate several next to each other therefore allowing a second dimension to the 'array'.

A simpler version if you don't need the array after the end of the function would be:

 int matrix[rows][cols];


来源:https://stackoverflow.com/questions/13099972/allocating-2-d-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!