Firstly, because the
for() looping condition is
k < size/2
only the
else branch will be entered.
This is because
k == size/2
will never be true inside the
for() loop.
Secondly, if your program crashes due to a segmentation fault (I did not test your program to see) then it means you are using bad pointers.
A bad pointer points to memory that you may not modify the contents of.
For example:
1 2 3 4
|
int a[5];
// available: a[0] a[1] a[2] a[3] a[4]
// NOT available: a[5]
|
In the code above, trying to modify
a[5]
may result in a crash because it is not a valid element of array
a
.
With this in mind, if we look at your code, we see:
12 13 14 15 16 17
|
swap(ip[k], ip[size-k]); // what if k == 0? then:
swap(ip[0], ip[size]); // oops, ip[size] is invalid just like a[5]
// so the correction is:
swap(ip[k], ip[size - k - 1]);
|
By the way, you are using
std::swap() from the
algorithm library.
This is the problem in
using namespace std;
and why many programmers avoid it.
The
algorithm header (which declares
std::swap() in C++98) is indirectly included by the
iostream header.
Without
using namespace std;
you would always need to qualify things from the C++ library accordingly: by adding the
std:: prefix.
This would improve the clarity of your code: you wouldn't use elements of the C++ library "by mistake" and other programmers would instantly recognize which elements are provided by the C++ library and which ones you wrote yourself.
1 2 3 4 5 6
|
#include <algorithm>
// using namespace std; // don't
// ...
std::swap(ip[k], ip[size - k - 1]);
|
Finally, you want to use
swapNum(), do you not?