BobbyPi BobbyPi - 2 months ago 8
C Question

Add element to array member of a struct

I have an union:

typedef union { int arr1[5]; char arr2[5]; } type


and a struct:

typedef struct { int size; type elt; } foo


and finally a variable:

foo bar = { 3, {1,2,3} }
.

I want to add an element to bar. Therefore I defined:

void myfun(foo x, int new)
{
x.elt.arr1[x.size] = new;
x.size += 1;
return;
}


If I call
myfun(bar,4)
it should change bar appropriately. But if I view the elements of
bar
before and after the call of
myfun
it will print
bar
without the additional element.

Edit: My view function is:

void myprint(foo x)
{
for ( int i = 0; i < x.size; i++) {
printf("%d ", x.elt.arr1[i]);
}
return;
}


What's my fault?

Answer

As interjay wrote, you are not modifying bar, but just a coppy (that is created separately in memory everytime when function myfun is called). Look up difference between functions called by value and functions called by reference. What you need is:

void myfun(foo *x, int new) 
{
    x->elt.arr1[x->size] = new;
    x->size += 1;
    return;
}

and then:

myfun(&bar,4)

That way, variable bar will be edited.

Comments