Error: array initializer must be an initializer list or wide string literal in C Merge Sort program

Error: array initializer must be an initializer list or wide string literal in C Merge Sort program

我是 C 的新手,我正在尝试制作一个基本的归并排序程序。当我编译这段代码时(使用 GCC)

int join(int arrayA[],int aLength,int arrayB[],int bLength)
{
    int array[aLength+bLength];
    int uptoA = 0; int uptoB = 0;//the upto variables are used as the index we have reached
    while ((uptoA < aLength) && (uptoB < bLength))
    {
        if (arrayA[uptoA] < arrayB[uptoB])
        {
            array[uptoA+uptoB] = arrayA[uptoA];
            uptoA++;
        } else {
            array[uptoA+uptoB] = arrayB[uptoB];
            uptoB++;
        }//else
    }//while

    if (uptoA!=aLength)//if A is the array with remaining elements to be added
    {
        for (int i = uptoA+uptoB; i < aLength+bLength; i++)
        {
            array[i] = arrayA[uptoA];
            uptoA++;
        }
    } else {//if B is the array with elements to be added
        for (int i = uptoB+uptoA; i < aLength+bLength; i++)
        {
            array[i] = arrayB[uptoB];
            uptoB++;
        }//for
    }//else

    return array;
}//int join

int merge_sort(int array[],int arrayLength)
{
    if (arrayLength <= 1)
    {
        return array;
    }
    if (arrayLength == 2)
    {

        if (array[0] > array[1]) {return array;}//if it's fine, return the original array
        int returningArray[2]; returningArray[0] = array[1]; returningArray[1] = array[0]; //just makes an array that is the reverse of the starting array
        return returningArray;

    }

    int aLength = arrayLength/2;
    int bLength = arrayLength - aLength;
    //now I will create two arrays with each of the halves of the main array
    int arrayAunsorted[aLength];
    int arrayBunsorted[bLength];
    for (int i = 0; i < aLength; i++)
    {
        arrayAunsorted[i] = array[i];
    }
    for (int i = aLength; i < arrayLength; i++)//this goes from the end of arrayA to the end of the main array
    {
        arrayBunsorted[i] = array[i];
    }

    int arrayA[aLength] = merge_sort(arrayAunsorted,aLength);
    int arrayB[bLength] = merge_sort(arrayBunsorted,bLength);
    printf("I can get this far without a segmentation fault\n");

    return join(arrayA,aLength,arrayB,bLength);

}

我知道这段代码的某些部分很糟糕,形式也很糟糕,但是一旦我让程序实际运行,我就会修复它。我是 C 的新手,所以我希望这不是一个愚蠢的问题。

这是不正确的:

int arrayA[aLength] = merge_sort(arrayAunsorted,aLength);

首先,你不能通过调用函数来初始化数组。正如错误消息所说,您只能使用初始化列表初始化数组,例如:

int arrayA[aLength] = {1, 2, 3};

或像这样的字符串文字:

char str[] = "abc";

其次,merge_sort 甚至 return 都不是一个数组,它 return 是 int。函数不可能 return C 中的数组,因为数组不能赋值。

join 也不正确。您已将其声明为 return int,但最后它声明为:

return array;

当你 return 一个数组时,它被转换为一个指针,所以它实际上是 returning int*,而不是 int。但是你不能return一个指向本地数组的指针,因为当函数returns.

时数组的内存变得无效

排序函数应该修改调用者传递给它们的数组。要么就地对数组进行排序,要么调用者应提供两个数组:一个包含输入数据,另一个应填充结果。

我不会尝试重写你所有的代码,它太烂了而且我没有时间。有很多资源展示了如何在 C 中实现归并排序。