gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:30:39 26 4
gpt4 key购买 nike

我不确定如何解释这一点,但下面这段代码可以完美编译,但是当你运行它时,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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com