0

I want to swap two argument's value. But I failed to achieve it by swapping their address in the function. At first, I supposed the address can be changed in function. But after debugging, I found that though the addresses had been changed in the function, it didn't change in the main function. Why does the pointer's address do in function like what the argument's value? Do ,only change the copy?

include<stdio.h>
void swap(int *, int *);
int main()
{
  int a = 5 , b = 10;
  swap(&a, &b);
  printf("%d", a);
  printf("\n%p", &a);
  return 0;
}

void swap(int *a, int *b)
{
  int *temp ;
  temp = a;
  a = b;
  b = temp;

}

Now I have learned one of the way to solve it. But who can tell me how to solve it by second rank pointer.

#include<stdio.h>
void swap();
int main()
{
  int a = 5 , b = 10;
  swap(&a, &b);
  printf("%d", a);
  printf("\n%p", &a);
  return 0;
}
void swap(int *a, int *b)
{
  int temp ;
  temp = *a;
  *a = *b;
  *b = temp;
}
sreepurna
  • 1,562
  • 2
  • 17
  • 32
Ghoster
  • 75
  • 10

1 Answers1

3

In first snippet swapping will not take place as you are swapping automatic local pointers which will no longer exist once function call return. This modification to the local pointers in swap function will not be seen in the main function.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • Thank you!I have found the specific answer in the other question.But I am also grateful for your help! – Ghoster Mar 03 '17 at 15:08