0

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;
}
1
  • 2
    A list doesn't contain any pointers to nodes until you add them. You'd need to allocate a node for x to point to, then set p to point to the node. Only then can you start accessing the value. So, p->ptr = x; is more plausible than the reverse assignment, but you still have to connect all the dots. Commented Apr 23, 2016 at 19:15

1 Answer 1

1

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;   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.