C 指针和内存分配 : Realloc Arrays and Pointer Passing

标签 c pointers memory-management reference

对于那些有 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/

相关文章:

c - 将一个链表指向另一个链表

c - C中的灵活结构

c++ - 如何返回私有(private)指针成员变量

c++ - C++中的未知构造/变量声明

c - 在 C 中取消引用较低级别的指针

objective-c - NSArray 是否复制对象?

c - 这段c代码有什么问题?答案总是零?

c - C中的大型二维数组

内存管理困惑: global char * in C program

c - 从 .h 头文件中删除预编译指令