错误:数组初始值设定项必须是C合并排序程序中的初始化列表或宽字符串文字

时间:2017-09-22 14:53:36

标签: c gcc mergesort

我是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很新,所以我希望这不是一个愚蠢的问题。

1 个答案:

答案 0 :(得分:1)

这是不正确的:

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

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

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

或字符串文字,如:

char str[] = "abc";

其次,merge_sort甚至不返回数组,它返回int。函数无法在C中返回数组,因为无法分配数组。

join也不正确。你声明它返回int,但最后它会:

return array;

当你返回一个数组时,它会被转换为一个指针,所以它实际上是返回int*而不是int。但是您无法返回指向本地数组的指针,因为当函数返回时,数组的内存将变为无效。

排序函数应该修改调用者传入的数组。对数组进行排序,或者调用者应该提供两个数组:一个包含输入数据,另一个应该用结果填充。

我不会尝试重写你的所有代码,它太破碎而且我没有时间。有许多资源显示如何在C中实现合并排序。

相关问题