+ 3
Swapping two numbers, what is the mistake in the code the numbers are not swaped??
#include<iostream> using namespace std; void swap(int,int); int main( ) { int a,b; cout"enter the values of a and b"<<endl; cin>>a>>b; swap(a,b); cout<<"swap values of a and b are"; cout<<a<<b; } void swap(int x,int y) { int temp; temp=x; x=y; y= temp; }
7 Respostas
+ 9
Hi Amit Vishwakarma ,
Your mistake in the method argument.
You must take a pointer to integer not a local variable.
void swap(int * x, int * y){
int temp;
temp = *x;
*x = *y;
*y = temp;
return;
}
and when you call the method you must put the address opterator &
As:
sawp(&a, &b);
hope this help you..
+ 6
without using pointers, the local variable inside the function is changed, but the actual value of the a and b( in your case) don't change.
+ 5
You can just write 'int &' instead of 'int' in your declaration and definition of swap, then it works.
+ 4
Because methods store local variables in the stack as a copy and when it finish the values will be released from memory.
But when you use pointer the method will store the value in the dynamic memory by using their address.
+ 2
But why can't we do without using pointer
+ 1
without using poiters you are passing the argument by value.
But what is needed is their reference.
- 1
I update the code check it.