gpt4 book ai didi

c - 简单地创建一个数据结构,它怎么会发生段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 00:20:07 26 4
gpt4 key购买 nike

我有一个关于数据结构的简单程序,但它会出现段错误,这让我非常沮丧,因为我完全不知道为什么。任何人都可以指出有关此代码的任何内容(甚至不相关)吗?谢谢

#include <unistd.h>
#include <stdlib.h>

typedef struct prof
{
struct prof *next;
char c;
int x;
int y;
} profile;

profile *create_profile(char c, int i, int j)
{
profile *new_elem;
new_elem = (profile*)malloc(sizeof(profile));
if (new_elem == NULL)
return (NULL);
new_elem->next = NULL;
new_elem->c = c;
new_elem->x = i;
new_elem->y = j;
return (new_elem);
}

int main()
{
profile **king = NULL;
*king = create_profile('K', 1, 1);
return 0;
}

最佳答案

你的国王是一个指向结构指针的指针。您需要一些地方来存储指向结构的指针,但那是您没有分配的地方。
您可以引入一个指针来解决这个问题。

int main()
{
/* introduce and NULL-init a pointer to struct */
profile* prince = NULL;
/* actually the init to NULL is not necessary,
because prince gets initialised later indirectly via king
(credits to alk), but it does not hurt and initialising everything
is a good habit. */

/* Introduce a pointer to pointer to struct,
initialised with the address of above pointer to struct,
the address of the above variable "prince" to be precise and clear.
The space for that automatic local variable is not dynamic,
it does not require a malloc. */
profile **king = &prince;

/* what the king is pointing to, i.e. the prince,
gets assigned what the function returns,
which is a cleanly allocated pointer to a new struct. */
*king = create_profile('K', 1, 1);

/* if king were still NULL, above statement would try to write
(the cleanly allocated pointer) into memory by dereferencing NULL ...
segfault!
(Well not necessarily, as alk points out, credits.
But dereferencing NULL is undefibed behaviour,
an almost guaranteed way to trouble in the long run
and in case a seggault is observed, a likely explanation.
*/
return 0;
}

关于c - 简单地创建一个数据结构,它怎么会发生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51800613/

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