bigTree
bigTree

Reputation: 2173

Changing a global structure in a function in C

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);    
}

Upvotes: 1

Views: 255

Answers (3)

Peng Yang
Peng Yang

Reputation: 231

Try to use void add_to_struct(struct myStruct **strct, char *val1, char *val2).

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 = "abcd";
    my_new->val2 = "efgh";
    my_new->next = strct;
    my_new->prev = NULL;   
    (*strct)->prev = my_new;
}

Upvotes: 1

nj-ath
nj-ath

Reputation: 3146

You're allocating memory using malloc and collecting the address of the memory using my_new variable. So the function is doing nothing effectively. Let me provide an anology. A man comes to ask water at your home. You should either take his bottle, fill it with water and give it back. Or you can give your own bottle to him filled with water. But you're simply taking your own bottle, filling it with water and keeping it to yourself.

You either have to do return my_new or use strct=malloc.... and also change argument of sizeof to myStruct

Upvotes: 1

Andras
Andras

Reputation: 3055

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.

Upvotes: 1

Related Questions