Sorry for asking a basic question, I am learning C and I got confused with assigning a value for a list. I got confused with my own question that pops into my head.. 🙁
So for instance, I have a struct below
typedef struct {
int value_in_use;
} structA;
typedef struct structB {
structA conn;
struct structB *next, *prev;
} structB
typedef struct {
structB *head, *tail;
} structC;
and I want to assign the value of “value_in_use” equal 1. I am totally confused, as what I understand, that in a list, I need to traverse from the head first(StructC), and I need to go inside the list until I get into structA and assign value to it. So something like
structC *C = NULL;
C = (structC *) malloc(sizeof(structC));
int assign=1;
&C->structB.head->conn.value_in_use=assign;
Meanwhile, I was thinking that I can actually assign a pointer to structA directly and assign value to it. So I can just say
structA *ue = NULL;
ue = (structA *) malloc(sizeof(structA));
ue->value_in_use = 100;
How does it differ for assigning the value of a list in run time in the first part and second part? I believe I can use both for assigning value (or?) ..
Thank you so much for sharing your knowledge with me.
The first one in fact won’t actually work. You’re trying to follow a head pointer from C, but you have no idea where that pointer points to (i.e. malloc is not recursive).
For the first case, you would need to do something like this:
Note that we do not have to allocate a structA separately, since there is one embedded in B.