Простой способ выделить память для "2-мерной" структуры так, как вам нужно:
#include <stdlib.h> /* for malloc() */
char **r;
/* we will allocate 'size' values, each of 'data_size' length */
size_t size = 10;
size_t data_size = 42;
size_t i;
/* allocate 'size' objects of the right type.
*
* Notes:
*
* 1. no casting the return value of malloc(),
* 2. r = malloc(size * sizeof *r) is type-agnostic, so
if you change the type of r, you don't need to remember
to change the malloc() call */
r = malloc(size * sizeof *r);
/* Error check omitted for clarity. In real code, always check for return
value of malloc() */
for (i=0; i < size; ++i) {
/* once again, no cast, and we use x = malloc(size * sizeof *x) idiom */
r[i] = malloc(data_size * sizeof *r[i]);
}
Преимущество вышеупомянутой схемы заключается в том, что она работает с минимальными усилиями для 3-, 4- или более крупных размеров и также легче читается.
В приведенном выше коде в цикле я мог бы написать malloc(data_size)
вместо malloc(data_size * sizeof *r[i])
, потому что sizeof(char)
гарантированно будет равно 1, но опять же, я предпочитаю приведенную выше форму, потому что она не зависит от типа.