Hi all,
When I was compiling this code in Linux with g++, I got the Segmentation Fault. I guess I might have
misused the pointer in my function. Could you help me figure out what's wrong with my code?
What this code should do is swapping the values of int a and int b with function swap...
Code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
void swap(int *p, int *q)
{
int *temp;
*temp=*p;
*p=*q;
*q=*temp;
}
int main()
{
int a=5,b=10;
int *p=&a;
int *q=&b;
swap(p,q);
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
return 0;
}
While a neat mathematical trick, it seems more likely to be less efficient in most cases. Assuming, of course, that the types being swapped even support the operation.
It works for the same reasons it works with operator-. This has the advantage of working on ANY pod type. On non POD types there are no guarantees (ie assume it doesn't work).
In the real world, this is not very efficient, as pretty much every processor now has a single instruction swap built in (explicitly or implicitly).
template <class T>
void swap(T& a, T& b)
{
T c(a);
a=b;
b=c;
}
Notice the complete lack of pointers. Pointers are evil.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Bookmarks