I'm using the following swap function to swap two elements of an array. The element pointed to by 'x' and 'y' and the one right below it, to be particular (then i want x and y to point to the second of the swapped elements, hence i use auto increment). I use the following call in the main function to call the swap function:

swap(&a[x][y], &a[++x][y]);

And the swap function looks like this.

void swap(int* p, int* q)
{
 int temp;
  temp = *p;
 *p = *q;
 *q = temp;
 return;
}

I dunno where i've gone wrong- is it the improper usage of pointers or auto increment operator or both? I feel it's the code on line 5 that's the culprit.

Any suggestions?

Recommended Answers

All 3 Replies

> swap(&a[x][y], &a[++x][y]); pre-incrementing here is undefined behavior. Explanation can be found here.

commented: Solved the prob in a jiffy :) +1
commented: Indeed it is so +21

Thanks Aia! that solved the problem. :)

lexicographical order of elements

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.