+ 1

Why we are using dereferncing variable while swapping

I just wrote code for swapping two integers and it works fine but I used a function swap in it whose arguments were pointer variables By pointer variables I understand they store address of a variable but Inside swap function while swapping with temp variable I didn't use pointer variables I mean I used *variable I am not getting itMeans if we use dereferncing * then how it is swapping values without swapping refrences Attaching code in answers

19th Aug 2021, 7:18 AM
Viraj
Viraj - avatar
5 Antworten
+ 2
Guru patel thank you for clarifying. Some programs do swap pointers instead of values when they are sorting strings or data structures. Though in those cases the original variables from the caller are also pointers, and the dereferencing technique (*p) is still used the same way in swap(). If you remove dereferencing in swap() then only the local pointers (address values) p and q get swapped and no change occurs outside of the swap() function.
19th Aug 2021, 8:17 AM
Brian
Brian - avatar
+ 1
A pointer variable (p) stores a memory address. When you dereference a pointer variable (*p) you access the memory location of the memory address. Your swap() function is simply swapping values. It uses pointers to determine exactly where in memory those values are stored, and the pointers are dereferenced in order to get at the actual values.
19th Aug 2021, 7:53 AM
Brian
Brian - avatar
+ 1
Brian I mean why we are not using something like this : temp=p; p=q; q=temp; I thought if we use above then it would swap references instead of values
19th Aug 2021, 7:57 AM
Viraj
Viraj - avatar
0
#include<iostream> using namespace std; void swap(int*,int*); int main() { int a=5; int b=6; swap(&a,&b); cout<<"value of a after swapping is :"<<a<<endl; cout<<"value of b after swapping is :"<<b<<endl; return 0; } void swap(int*p,int*q) { int temp; temp=*p; *p=*q; *q=temp; }
19th Aug 2021, 7:18 AM
Viraj
Viraj - avatar
0
Ipang sorry I edited now 😅😅
19th Aug 2021, 7:27 AM
Viraj
Viraj - avatar