#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define MAX_DATA 512
struct Child {
int id;
int set;
char name[MAX_DATA];
char email[MAX_DATA];
};
struct Database {
int max_rows;
int max_data;
struct Child *rows;
};
struct Child *
Allocate_childs(int max_rows)
{
struct Child *rows = malloc(max_rows * sizeof(struct Child));
assert(rows != NULL);
return rows;
}
struct Database *
Allocate_database(int max_rows)
{
struct Database *db = malloc(max_rows * sizeof(struct Child) + sizeof(struct Database));
assert(db != NULL);
return db;
}
int main(int argc, char *argv[])
{
int max_rows = 100;
if (argc > 1) {
max_rows = atoi(argv[1]);
}
struct Child *rows = Allocate_childs(max_rows);
struct Database *db = Allocate_database(max_rows);
db->rows = rows;
db->max_rows = max_rows;
printf("sizeof rows: %lu\n", sizeof(*rows));
printf("sizeof db: %lu\n", sizeof(*db));
printf("sizeof db (correct?): %lu\n", sizeof(*db) + sizeof(*rows));
return 0;
}
Правильно ли я понял, что sizeof() в коде выше выдает не то, что я желаю и надо считать ручками? Т.е. верно считать sizeof(*db) + sizeof(*rows)
. Или может я что-то не понял? Нужно создавать структуры с динамическим массивом другой структуры. Погуглил, но ответа точного не нашел. Про VLA знаю, но пока хочу сделать все по-старинке.