问题
I had recently been for a interview and they had asked me to write a programe to allocate memory dynamically for a two dimensional array (i=3 and j=2)
回答1:
int *a = (int*)malloc(i*j*sizeof(int));
You can get a[k][l]
with a[k*i+l];
回答2:
Some of you will hate this, but it is a favorite of mine. The main advantage is that it can be de-allocated through a single free
and still allows for access through A[r][c]
.
#include <stdlib.h>
int main(void)
{
int num_row = 3, num_col = 2, r;
int ** A;
A = malloc(num_row*(sizeof(*A)+num_col*sizeof(**A)));
for (r = 0; r < num_row; r++)
{
A[r] = (int*)(A+num_row)+r*num_col;
}
/* Accessing element at row r and column c is through:
*
* A[r][c].
*/
free(A);
return 0;
}
回答3:
int i = 3;
int j = 2;
int** a = malloc(i * sizeof(int*));
for (unsigned int k = 0; k < i; k++) {
a[k] = malloc(j * sizeof(int));
}
// Now you can use it.
a[0][0] = 0;
a[2][1] = 3;
Haven't you tried searching the SO question database before asking the question?
来源:https://stackoverflow.com/questions/17134650/how-to-allocate-memory-dynamically-for-a-two-dimensional-array