Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Changing a global structure in a function in C without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I defined a structure as follows:
typedef struct myStruct{ char *val1; char *val2; struct myStruct *prev; struct myStruct *next; } myStruct;
I also wrote a function to add a node to this structure:
void add_to_struct(struct myStruct *strct, char *val1, char *val2){ // create the node for new element struct myStruct *my_new = malloc(sizeof(struct myStruct)); my_new->val1 = val1; my_new->val2 = val2; my_new->next = strct; my_new->prev = NULL; strct->prev = my_new; }
Adding a node to the struct using this function doesn’t seem to work though. I guess the problem is that I do not pass my structure (which I defined as a global variable) by reference correctly, but I don’t know why. Any idea what I am doing wrong?
EDIT How I call it:
void main(){ struct myStruct *headPrev = Malloc(sizeof(struct myStruct *)); struct myStruct *headNext = Malloc(sizeof(struct myStruct *)); char *headval1 = Malloc(sizeof(char) * MAXLEN); char *headval2 = Malloc(sizeof(char) * MAXLEN); my_struct = Malloc(sizeof(struct myStruct)); my_struct->prev = headPrev; my_struct->next = headNext; my_struct->val1 = headval1; my_struct->val2 = headval2; newVal1 = "abcd"; newVal2 = "bl"; .... add_to_struct(my_struct,newVal1,newVal2); }
Answer
looks pretty close, just a few minor issues —
my_new should be allocated to be sizeof(struct myStruct)), not cacheElement, no?
also, this looks like a linked list, but you need to return my_new so you can use it as the new head of list.
We are here to answer your question about Changing a global structure in a function in C - If you find the proper solution, please don't forgot to share this with your team members.