0

This is a very basic question, and I think I'm still misunderstanding something very basic.. In my work, I'm trying to use a code someone else wrote in the past and seeing an error I'm having trouble to solve.
Below is the code. I get error in function Partition2. in line float pivot = arr[left][0];. I tried float pivot = *(*(arr+left)+0); but it's the same. I know arr is of type float[300][1]. How can I use the function with smallest modification?

in test.c

#define post_nms_topN 300
float unit_bbox_pred[post_nms_topN][4];
float unit_cls_prob[post_nms_topN][1];
...
main()
{
...
    QuickSort2((float **)unit_cls_prob,0,post_nms_topN-1,(float **)unit_bbox_pred);
..
}

in QuickSort2.c

...
int Partition2(float **arr, int left, int right, float **prop)
{
    float pivot = arr[left][0];   // <=== seg. fault
    //float pivot = *(*(arr+left)+0);

    int low = left+1;
    int high = right;

    while(low <= high)   
    {
        while(pivot <= arr[low][0] && low <= right)
            low++;

        while(pivot >= arr[high][0] && high >= (left+1))
            high--;

        if(low <= high)    
            Swap2(arr, low, high, prop);    
    }
    Swap2(arr, left, high, prop);
    return high;
}

void QuickSort2(float **arr, int left, int right, float **prop)
{
    int pivot;
    if(left <= right)
    {
        pivot = Partition2(arr, left, right, prop); 
        QuickSort2(arr, left, pivot-1, prop);
        QuickSort2(arr, pivot+1, right, prop);
    }
}
Chan Kim
  • 5,177
  • 12
  • 57
  • 112
  • 1
    Two-dimensional arrays are not equivalent to pointers-to-pointers. Note that even one-dimensional arrays are not really equivalent to pointers, though the names of a one-dimensional array will act like pointer to the elements in most cases. The names of two-dimensional arrays will act like a pointer to a one-dimensional array in most cases (but *not* like pointers-to-pointers). – Michael Burr Nov 11 '16 at 07:08
  • Remove the the cast and fix the code until it compiles quietly without. – alk Nov 11 '16 at 07:25

1 Answers1

2

I think I'm still misunderstanding something very basic

Indeed. Pointer-to-pointers are not 2D arrays, nor can they be used to point at 2D arrays. This is a common misunderstanding, because we can often use a regular pointer in place of a 1D array. We would get a pointer to the first element. Yet an array is not a pointer, see Is an array name a pointer in C?

The first element of a 2D array is an array, and not a single item. You cannot set a pointer-to-pointer to point there, because a pointer-to-pointer could only be used against an array of pointers, which is something entirely different.

As for how to fix your function, see Ways to pass 2D Array to function in C. There's a code example as well as a more in-depth explanation about how arrays "decay" when used as function parameters.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396