对于那些有 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()
产生段错误。
最佳答案
这个套路应该是
void init_file(configfile **cf) {
*cf = malloc(sizeof(configfile));
(*cf)->numsections = 0;
(*cf)->sections = NULL; // You forgot to initialise this.
}
即由 init_file(&myconfigfilepointer);
调用,因此 malloc
返回值被传回。
需要为init_sec
做同样的事情
此函数不正确 - 这是更正后的版本
void add_sec(configfile *cf, configsection *sec) {
// Increase the size indicator by 1
// Reallocate the array to accommodate one more item
cf->sections = realloc(cf->sections, sizeof(configsection)*(1 + cf->numsections));
// Insert the new item
cf->sections[cf->numsections] = *sec; // Since arrays start at 0
cf->numsections = cf->numsections + 1;
}
然后您需要调整 main
中的调用
关于C 指针和内存分配 : Realloc Arrays and Pointer Passing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9443617/