Passing a variable to function by reference [Solved]

3 posts / 0 new
Last post
Nube
Nube's picture
Offline
Last seen: 6 days 6 hours ago
Joined: 2012-09-10 02:09
Passing a variable to function by reference [Solved]

I try to pass a variable by reference to a function and change its value. Inside that function it works but when I print the value of the variable outside the function the value is different.. I'd like to understand what I am doing wrong as I need it for my program..

I declare this variable as global plus the definition of two functions outside (before) the main function:

  1. int a;
  2.  
  3. void change_sound_1(int *);
  4. void change_sound_2(int *);
  5.  
  6. .....

inside the main function i have this code:

  1. switch(code)
  2. {
  3. case 0:
  4. IDOS->Printf("Sound rate is: 11025\n");
  5. change_sound_1(&sound_code);
  6. IDOS->Printf("sound_code is:%d\n", sound_code);
  7. break;
  8.  
  9. case 1:
  10. IDOS->Printf("Sound rate is: 22050\n");
  11. change_sound_2(&sound_code);
  12. IDOS->Printf("sound_code is:%d\n", sound_code);
  13. break;
  14. }
  15.  
  16. break;

These are the two functions that I use to modify the int variable:

  1. void change_sound_1(int *a){
  2. *a=0;
  3. printf("sound code is:%d\n", *a);
  4. *a=*a+1;
  5. printf("sound code is:%d\n", *a);
  6. }
  7.  
  8. void change_sound_2(int *b){
  9. *b=0;
  10. printf("sound code is:%d\n", *b);
  11. *b=*b+2;
  12. printf("sound code is:%d\n", *b);
  13. }

But when i print the variable, for the second time, in the main function, it prints 0 (zero).. Shouldn't it print the the same value that the two functions print? as I have modified its value using the pointer??

thomas
thomas's picture
Offline
Last seen: 5 hours 4 min ago
Joined: 2011-05-16 14:23
Re: Passing a variable to function by reference

cross-post: http://www.amigans.net/modules/xforum/viewtopic.php?forum=25&topic_id=7822&order=

Nube
Nube's picture
Offline
Last seen: 6 days 6 hours ago
Joined: 2012-09-10 02:09
Re: Passing a variable to function by reference

Yes Thomas, i posted it both here and there :-)
Thanks to all

Log in or register to post comments