问题
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