c - 指向结构指针的指针让人头疼。 .

标签 c

我不确定如何解释这一点,但下面这段代码可以完美编译,但是当你运行它时,SIGSEV。 拜托,谁能准确地说出我哪里出错了? 事实上,我希望能够按如下索引访问元素,同时能够使用结构。

#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;
}

最佳答案

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

sample->p[sample->id]->name = _name;

在您的程序中,您没有为 person 结构内的 p 数组分配内存。因此,此值将始终为 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);
  }
  ...
}

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

关于c - 指向结构指针的指针让人头疼。 .,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5395391/

相关文章:

c - 如何根据数据大小有条件地编译C代码?

C - 程序崩溃执行

子进程可以等待其兄弟进程并获取其退出状态吗?

c - 如何防止 malloc.c 3096 SYSMALLOC : assertion failed while using fscanf to build an array from a port?

c - C 中的堆分配

c - 如何在 Linux 中使用参数执行 C 代码中的外部程序?

c - 编译器如何知道 C 中的指针地址是端口映射还是 RAM?

c - (C) 从调用其他函数的函数打印结构数组

c - Xcode 中缺少 c.h?

c - 如何将一个元素插入到已经占用的数组中?