C Указатель и распределение памяти: массивы Realloc и прохождение указателя
Для тех, кто имеет опыт работы с C, это будет простая проблема выделения / обращения к памяти:
Вот мои структуры данных:
struct configsection {
char *name;
unsigned int numopts;
configoption *options;
};
typedef struct configsection configsection;
struct configfile {
unsigned int numsections;
configsection *sections;
};
typedef struct configfile configfile;
Вот мои процедуры для инициализации раздела конфигурации или файла конфигурации и для добавления раздела конфигурации в файл конфигурации:
// Initialize a configfile structure (0 sections)
void init_file(configfile *cf) {
cf = malloc(sizeof(configfile));
cf->numsections = 0;
}
// Initialize a configsection structure with a name (and 0 options)
void init_sec(configsection *sec, char *name) {
sec = malloc(sizeof(configsection));
sec->numopts = 0;
sec->name = name;
printf("%s\n", sec->name);
}
// Add a section to a configfile
void add_sec(configfile *cf, configsection *sec) {
// Increase the size indicator by 1
cf->numsections = cf->numsections + 1;
// Reallocate the array to accommodate one more item
cf->sections = realloc(cf->sections, sizeof(configsection)*cf->numsections);
// Insert the new item
cf->sections[cf->numsections] = *sec;
}
Я считаю, что моя проблема возникает в моей функции init_sec (). Вот пример:
int main(void) {
// Initialize test configfile
configfile *cf;
init_file(cf);
// Initialize test configsections
configsection *testcs1;
init_sec(testcs1, "Test Section 1");
// Try printing the value that should have just been stored
printf("test name = %s\n", testcs1->name);
Хотяprintf()
вinit_sec()
успешно печатает имя, которое я только что сохранил в разделе конфигурации, пытаясь сделать то же самое вprintf()
изmain()
производит ошибку сегментации. В дальнейшем,addsec()
производит ошибку сегментации.