Reputation: 3
My question is how would I access the num variable in a node struct of a list struct? I tried two ways and both of them didnt work? Im just curious to why that is. Thank you to anyone who helps I know this is a novice question. Im fairly new to c and stack overflow, hopefully I can learn much from this website.
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int num;
struct node *next;
} node;
typedef struct list
{
node *ptr;
struct list *next;
} list;
int main()
{
list *p = malloc(sizeof(list));
//p->ptr->num = 5;
node *x;
x = p->ptr;
//x->num = 5;
return 0;
}
Upvotes: 0
Views: 1549
Reputation: 7542
What you were trying to do is correct, but the problem is that though you have allocated memory for list
, no memory is allocated for the node
residing inside list
.
list *p = malloc(sizeof(list));
//p->ptr->num = 5;
node *x;
p->ptr = malloc(sizeof(node));
x = p->ptr;
x->num = 5;
Upvotes: 1