【问题标题】:How to use an array of pointers inside a structure correctly如何正确使用结构内的指针数组
【发布时间】:2013-04-08 00:42:54
【问题描述】:

正如您在下面的代码中看到的那样,我有两个结构父子结构。父结构有一个子类型的指针数组。程序进入 for 循环时出现分段错误。我的代码有什么问题吗? 我不想使用方括号的原因是我有一个函数,它接受一个子类型的指针参数,我想将每个子指针传递给该函数而不需要使用 &。

任何帮助将不胜感激 谢谢

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
   int id;
} child;

typedef struct {
   child** c;
} parent;

int main(int argc, char **argv) {
    int number_of_children = 5;

parent* p = (parent*)malloc(sizeof(parent));

p -> c = (child **) malloc(number_of_children * sizeof(child*));

int i;
for(i=0; i<number_of_children; i++)
    p -> c[i] -> id = i;
}

【问题讨论】:

  • 您还需要为child*s 指向的内容分配内存。

标签: c pointers memory-management malloc structure


【解决方案1】:

您正确分配了子指针表,但没有分配任何子表。

int i
for(i = 0; i < number_of_children; ++i) {
    p->c[i] = (child *) malloc(sizeof(child));
    p -> c[i] -> id = i
}

【讨论】:

  • 非常感谢,问题已解决
【解决方案2】:

未经测试,但应该是这样的:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
   int id;
} child;

typedef struct {
   child** c;
} parent;

int main(int argc, char **argv) {
    const int number_of_children = 5;

    parent* p = malloc(sizeof(parent));
    if(p == NULL) halt_and_catch_fire();

    p->c = malloc(number_of_children * sizeof(child*));
    if(p->c == NULL) halt_and_catch_fire();    

    for(int i=0; i<number_of_children; i++)
    {
        p->c[i] = malloc(sizeof(child));
        if(p->c[i] == NULL) halt_and_catch_fire();

        p->c[i]->id = i;
    }

    // free() *everything* allocated
}

正如我们所看到的,您正在尝试分配一个分段的指针对指针的东西,这没有明显的需要,因为您不会分配超过一个最内层的对象。如果你想创建一个多维数组,你不应该把分段弄得一团糟,do like this instead

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多