1

i have inline c swap function for sorting an array but in the compile time it gives error that swap reference is undefined. by removing the swap it works; what is wrong with code

inline void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void sort(int ar[])
{
    int length = sizeof(ar) / sizeof(int);
    for(int i = 0; i < length; i++)
    {
        for(int j = i; j < length; j++)
        {
            if(ar[j] < ar[i])
            {
                swap(&ar[j], &ar[i]);
            }
        }
    }
}
hellow
  • 12,430
  • 7
  • 56
  • 79
  • 2
    You can't get the length of a passed array with `sizeof`. You have to explictly pass it via a parameter. – hellow Oct 19 '18 at 08:25
  • 2
    Unrelated to your problem, but `sizeof(ar) / sizeof(int)` is flawed. It's because `ar` is a *pointer*, and doing `sizeof` on a pointer returns the size of the pointer itself and not the data it points to. You need to explicitly pass the size of your array as an argument to the function. – Some programmer dude Oct 19 '18 at 08:26
  • use this before function definition.. void swap(int *, int *) __attribute__((always_inline)); – Pandey Amit Oct 19 '18 at 08:47
  • @amitpandey That is *very* compiler dependent. – Some programmer dude Oct 19 '18 at 08:50

1 Answers1

-1
int length = sizeof(ar) / sizeof(int);

Pass the length of your array instead of trying to do something (that won't work).

Remove the inline, it's not relevant and causes your issue. If the compiler can optimize this, it will inline it, otherwise it's just an advice you give the compiler, nothing more.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62