指向结构的指针让人头疼..

Kha*_*011 4 c

我不知道如何解释这个但是这段代码可以完美编译,但是当你运行它时,SIGSEV.请问,任何人都可以准确地告诉我哪里出错了吗?事实是我希望能够通过索引访问元素,如下所示,同时能够使用struct.

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

/* This is a struct describing properties of an element */
struct element{
    int age;
    char* name;
};

/* This struct contains a pointer to a pointer on a element "struct element" */
struct person{
    struct element** p;
    int id;
};

/* Thus function initializes a struct person by allocation memory for it */
struct person* init(int size)
{
    struct person* sample = (struct person* )malloc(size*sizeof(struct person));
    sample->p = NULL;
    sample->id = 0;
    return sample;
}

/* use this function to insert a new element in the struct */
void insert(struct person* sample, char* _name, int _age)
{
    sample->p[sample->id]->name = _name; /* the program crashes here  according to the debugger , but why?? */
    sample->p[sample->id]->age = _age;  /* of course, this will cause trouble too because it has the same construct as the previous one */
    sample->id++;
}


/* main entry */
int main()
{
    struct person* student = init(10); /* Allocating space for 10 students */
    insert(student, "kido", 8);
    printf("Your name is %s and your age is %d", student->p[0]->name, student->p[0]->age); /* we can't write student->p->name */
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 5

问题在于insert您在问题中标记的代码行中的方法

sample->p[sample->id]->name = _name;
Run Code Online (Sandbox Code Playgroud)

您的程序中没有任何地方为结构p内部的数组分配内存person.因此,这个价值永远是NULL.尝试分配此值将正确导致程序崩溃.

要解决此问题,您需要确保p数组足够大以容纳表达式提供的索引sample->id.实现此目的的最佳方法是使用该realloc函数并添加一个字段person来存储p数组的大小

这是一个快速的样本.注意:为了简单起见,省略了错误检查和0内存初始化.

struct person{
    struct element** p;
    size_t length;
    int id;
};

void insert(struct person* sample, char* _name, int _age)
{
  if (sample->id >= sample->length) {
    sample->p = realloc(sample->p, sizeof(element*) * sample->id);
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

虽然名称和年龄总是通过sample->id字段索引,但看起来确实很奇怪.这表明它总是放在同一个位置,在这种情况下不需要数组.你能详细说明它应该如何运作吗?