1

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?

3
  • 2
    How do you "view the elements of bar"? Can you provide a stackoverflow.com/help/mcve ? Commented Sep 6, 2016 at 17:49
  • 7
    Function arguments are passed by value, so you aren't modifying the original structure but a copy. Commented Sep 6, 2016 at 17:51
  • change your call by reference (&) and modifiy a bit your function to use a pointer , and it should be ok Commented Sep 6, 2016 at 18:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, my bad. Edit that post if you find something wrong, I can't check it on this PC and I am horrible with syntax :D.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.