'Is there any other way to swap address of pointers to interchange value? [closed]
Is there any other way to swap address of pointers to interchange value ?
Below is one way to do the same. Here we are not changing values saved on address.
void Change_Address( int *&p, int *&pt)
{
int *pp;
pp = p;
p = pt;
pt= pp;
}
int main(void)
{
int a =3, b = 4, *p, *p1;
p = &a; p1 = &b;
printf("Values Before interchange %d %d\n", *p, *p1);
Change_Address(p, p1);
printf("Values after interchange %d %d", *p, *p1);
getch();
return 0;
}
Solution 1:[1]
Your code uses references which are C++, in C you would have to use pointer to pointer :
void Change_Address( int **p, int **pt)
{
int *pp;
pp = *p;
*p = *pt;
*pt= pp;
}
int main(void)
{
int a =3, b = 4, *p, *p1;
p = &a; p1 = &b;
printf("Values Before interchange %d %d\n", *p, *p1);
Change_Address(&p, &p1);
printf("Values after interchange %d %d", *p, *p1);
getch();
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zakinster |
