gpt4 book ai didi

c - 如何使用 {} 声明指针结构?

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

这可能是 C 编程语言中最简单的问题之一......

我有以下代码:

typedef struct node
{
int data;
struct node * after;
struct node * before;
}node;

struct node head = {10,&head,&head};

有没有一种方法可以使 head 成为 *head [使其成为指针] 并且仍然可以使用 '{ }' [{10,&head,&head}] 来声明 head 的实例并且仍然离开它在全局范围内?

例如:

 //not legal!!!
struct node *head = {10,&head,&head};

最佳答案

解决方案一:

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


typedef struct node
{
int data;
struct node * after;
struct node * before;
}node;
int main() {

struct node* head = (struct node *)malloc(sizeof(struct node)); //allocate memory
*head = (struct node){10,head,head}; //cast to struct node

printf("%d", head->data);

}

struct node *head = {10, head, head} 这样简单的东西是行不通的,因为你还没有为结构分配内存(int 和两个指针)。

解决方案 2:

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


typedef struct node
{
int data;
struct node * after;
struct node * before;
}node;
int main() {

struct node* head = &(struct node){10,head,head};

printf("%d", head->data);

}

这将超出范围 - 由于这个原因,解决方案 1 更优越,并且由于您正在创建链表,我相信您需要堆分配内存 - 而不是堆栈分配。

关于c - 如何使用 {} 声明指针结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718588/

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