-3

I have this very simple program

int test(int asdf){
  asdf = asdf + 1;
  return 0;
}

int main ( int argc, char **argv ){

  int a = 1;
  test(a);
  printf("a is %d\n", a);
}

I want the program to output 2, but instead it outputs 1. What went wrong? How should I pass the reference?

Mariska
  • 1,913
  • 5
  • 26
  • 43
  • @RaymondChen: Beware, the accepted answer to that question is nonsense. – Keith Thompson Oct 19 '14 at 01:33
  • @Keith: No, it's quite good, for solving a very different problem (how do I share an object with my callback function?). It simply isn't a duplicate. – Ben Voigt Oct 19 '14 at 01:33
  • Rats. I got it from [this question](http://stackoverflow.com/questions/12699712/why-doesnt-return-modify-the-value-of-a-parameter-to-a-function) which is a closer match to the question. – Raymond Chen Oct 19 '14 at 01:36
  • That's ok vote to close (because it has been answered already) but why all these downvotes rather just point to duplicate topic? – Jack Oct 19 '14 at 02:12
  • @Raymond: Yes, that one is a good duplicate. It doesn't have all the type erasure baggage, just gets to the point of transferring a result from function to caller. – Ben Voigt Oct 19 '14 at 02:42
  • @Jack I didn't downvote, but my guess is that the question has many duplicates, so the OP did not do sufficient research before asking. – Raymond Chen Oct 19 '14 at 02:49

3 Answers3

1

Whatever you pass is going to get copied... so you should pass something, that even when copied, lets you find the original a.

That something is a pointer, and its value is the address of a.

If you write your friend's address on a piece of paper, then no matter how many times that paper gets copied, the person holding it can still find the original house.

You write a pointer as int* asdf, and the address of a is written as &a. To find the object when you have a pointer, you need *asdf.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1

First get started with a Pointers chapter from good C book

int test(int* asdf){   // Argument will be pointer to integer
  *asdf = *asdf + 1;   // de-reference and access asdf's content & increment
  return 0;
}

test(&a); // Pass address of a
P0W
  • 46,614
  • 9
  • 72
  • 119
0

C doesn't support passing a variable by reference so you can't do that.

However, if you did pass a pointer to a variable then you could get the variable incremented.

Look at:

Passing by reference in C

Community
  • 1
  • 1
Avitus
  • 15,640
  • 6
  • 43
  • 53