Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pointers to swap int array values

Tags:

c

pointers

swap

I am supposed to use pointers to swap ints in an array. It compiles with no errors or warnings and runs but does not swap the ints. Any suggestions would be helpful!!!

Here is the tester:

#import <stdio.h>

void swap( int ary[] );

int main(  int argc, char*argv[] )
{
    int ary[] = { 25, 50 };
    printf( "The array values are: %i and %i \n", ary[0], ary[1] );
    swap( ary );
    printf( "After swaping the values are: %i and %i \n", ary[0], ary[1] );

    return 0;
}

Here is the swap function:

void swap( int ary[] )
{
    int temp = *ary;
    *ary = *(ary + 1);
    *ary = temp;
}

This is what is displayed after running:

The array values are: 25 and 50
After swaping the values are: 25 and 50
like image 804
Josh Curren Avatar asked Nov 03 '09 23:11

Josh Curren


People also ask

How do I swap values with pointers?

Logic To Swap Two Numbers using Pointers and FunctionWe pass the address of variable a and b to function swap(). Inside function swap() we take a local variable temp. Since address of variable a and b are passed to swap() method, we take 2 pointer variables *x and *y.

How do you swap the contents of an array?

Example 2: Using std::swap() to swap elements The built-in swap() function can swap two values in an array . template <class T> void swap (T& a, T& b); The swap() function takes two arguments of any data type, i.e., the two values that need to be swapped.

Can array and pointer be used interchangeable?

A common misconception is that an array and a pointer are completely interchangeable. An array name is not a pointer. Although an array name can be treated as a pointer at times, and array notation can be used with pointers, they are distinct and cannot always be used in place of each other.


3 Answers

I hate spoiling this but it looks like a typo more than anything.

In your swap function:

*ary = temp;

should be:

*(ary + 1) = temp;

edit: Is there a reason you're not using array notation? I think it's a bit clearer for things like this:

int temp = ary[0];
ary[0] = ary[1];
ary[1] = temp;
like image 134
Ron Warholic Avatar answered Sep 19 '22 09:09

Ron Warholic


Examine your swap function more carefully:

void swap( int ary[] )
{
    int temp = *ary;
    *ary = *(ary + 1);
    *ary = temp;
}

When does *(ary + 1) get assigned to?

like image 32
CB Bailey Avatar answered Sep 17 '22 09:09

CB Bailey


You move the second value into the first spot, and then move the first value back into the first spot.

like image 39
theycallmemorty Avatar answered Sep 18 '22 09:09

theycallmemorty