Click here to Skip to main content
14,774,516 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <stdio.h>
void func(int *x, int *y);
int x=1, y=2;

int main(){
  int x=3;
  func(&y, &x);
  printf("x=%2d y=%2d\n", x, y);
  func(&x, &y);
  return 0;
}

void func(int *x, int *y){
  x=y;
  *x=*x-2;
  *y=*y*2;
  printf("x=%2d y=%2d\n", *x, *y);
}


The expected output:

x=10 y=10
x=10 y= 2
x= 8 y= 8

What I have tried:

I am a beginner of C language and don't understand how pointer and functions work together.
Please, help me figure it out!!!
Posted
Updated 5-Sep-20 5:14am
v2

1 solution

I'd strongly recommend that you run this through the debugger, which will show you what is happening.

But ... start by looking at your code:

int x=1, y=2;          ----- This x is never used.
int main(){
  int x=3;             ----- This version of x hides the outer one;
  func(&y, &x);        ----- passes pointers to "2" and "3" respectively.

In the function, the outside world names are ignored:
void func(int *x, int *y){            --- So x points to "2" and y points to "3"
  x=y;                                --- Now x and y both point to the same place, 
                                          which contains "3"
  *x=*x-2;                            --- So both x and y now point to "3 - 2", or "1"
  *y=*y*2;                            --- And both x and y now point to "1 * 2" or "2"
  printf("x=%2d y=%2d\n", *x, *y);    --- So you get "x = 2, y = 2" printed.
}
When you get back to main both x and y contain "2" - because func never used the original value of the x pointer you passed in - it overwrote it instead.

Break out the debugger, and follow your code through - it'll become a whole load clearer!
How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900