OiO.lk Blog C# Static global pointer in struct.h is malloced by a function in struct.c, but it is NULL inside main()
C#

Static global pointer in struct.h is malloced by a function in struct.c, but it is NULL inside main()


struct.h

#ifndef STRUCT_H
#define STRUCT_H

struct linkedlist
{
    int data;
};

static struct linkedlist *head = NULL;

void build_linkedlist();
#endif

struct.c

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

void build_linkedlist()
{
    head = malloc(sizeof(struct linkedlist));
    head->data = 5;
    printf("inside build_linkedlist(): head = %p\n\n", head);
}

main.c

#include <stdio.h>
#include "struct.h"

int main()
{
    build_linkedlist();
    printf("inside main(): head = %p\n", head);
}

output

inside build_linkedlist(): head = 0x55ce669e62a0
inside main(): head = (nil)

Problem:

By calling build_linkedlist(), the head pointer is first allocated with an address, but when we access it in main(), its value is nil (I guess that means NULL).

How to resolve this?



You need to sign in to view this answers

Exit mobile version