BobbyPi BobbyPi - 1 year ago 59
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;

If I call
it should change bar appropriately. But if I view the elements of
before and after the call of
it will print
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]);

What's my fault?

Answer Source

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;

and then:


That way, variable bar will be edited.