2

I was doing this exercise and I had to write a program that takes in a list of numbers and swaps pairs of numbers so they're in order:

void swapPairs(int* a[], int length)
{
   int i=0;
   int temp;
   while(i<(length-1))
   {
     if(a[i]>a[i+1])
     {
        temp=a[i];
        a[i]=a[i+1];
        a[i+1]=temp;
     }
     i++;
   }
}

int main()
{
  int array[]={2,1,3,1};
  swapPairs(array, 4);
  return 0;
}

I keep getting these errors:

In function ‘swapPairs’:
warning: assignment makes integer from pointer without a cast
     temp=a[i];
         ^

warning: assignment makes pointer from integer without a cast
     a[i+1]=temp;


In function ‘main’: warning: passing argument 1 of ‘swapPairs’ from incompatible pointer type
swapPairs(array, 4);
         ^

note: expected ‘int **’ but argument is of type ‘int *’
void swapPairs(int* a[], int length)
  ^

When I tried it with just an array instead of a pointer, it worked perfectly fine. Can someone please explain what is wrong with this and how to fix it?
  Thanks in advance.

1
  • 2
    int* a[] change that to int a[] Commented May 10, 2015 at 21:51

2 Answers 2

2

Your declaration of swapPairs is wrong - it shouldn't accept an array of int * (int pointers) - it should accept and an array of ints:

void swapPairs(int a[], int length)
Sign up to request clarification or add additional context in comments.

5 Comments

my question had two parts; first i had to write it with int a[] as the parameter and then say how i would change it if the parameter instead was int* a[]. thats the part i m stuck on
@ajia that is also coincidentally the part you left out of your posted question. We're not mind-readers.
@ajia int *a[] is not "a list of numbers" as you said in your question. It would help if you showed the code which will call the version with int *a[]
I did. I have exactly the same code for both except the other one had just int a[] as a parameter instead.
nevermind. I think the question was wrong to begin with
1

The type of 'temp' is int. The type of 'a[i]' is *int (pointer to an int).

You are assigning the value of a pointer rather than the value of an integer because you are failing to dereference the pointer.

The while loop should read:

    while(i<(length-1))
    {
        if(*(a[i])>*(a[i+1]))
        {
             temp=*(a[i]);
             *(a[i])=*(a[i+1]);
             *(a[i+1])=temp;
        }
        i++;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.