BobbyPi
BobbyPi

Reputation: 121

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?

Upvotes: 1

Views: 77

Answers (1)

L. Zeda
L. Zeda

Reputation: 123

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.

Upvotes: 1

Related Questions