开发者

How can I declare a pointer structure using {}?

开发者 https://www.devze.com 2022-12-28 12:06 出处:网络
This probably is one of the easiest question ever in C programming language... I have the follo开发者_开发问答wing code:

This probably is one of the easiest question ever in C programming language...

I have the follo开发者_开发问答wing code:

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

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

Is there a way I can make head to be *head [make it a pointer] and still have the availability to use '{ }' [{10,&head,&head}] to declare an instance of head and still leave it out in the global scope?

For example:

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


Solution 1:

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

}

Something as simple as struct node *head = {10, head, head} is not going to work because you haven't allocated the memory for the struct (the int and two pointers).

Solution 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);

}

This will go out of scope - Solution 1 is superior for this reason and since you're creating a linked list, I believe you need heap allocated memory - not stack allocated.


You can make head a pointer, but you'll need to initialize it in a function.

struct node head_node;
struct node *head = &head_node;

void
initialize() {
    *head = {10,&head_node,&head_node};
}

There's no way you can initialize head ptr directly in global scope.

0

精彩评论

暂无评论...
验证码 换一张
取 消