多个定义,而不是标题?为什么地板返回双倍?

时间:2015-07-05 19:06:18

标签: c++ floor multiple-definition-error

我尝试使用静态数组编写合并排序函数,当然我有一个难以理解的错误。

所以第一个问题是,当我编译我的程序时,它在该代码的第9行给出了一个多重定义错误:

#include <cmath>
#include "include\sort.h"


/*
Theses fonctions accept only arrays of unsigned short int with a length in unsigned int
*/

unsigned short int* sortByFusion(unsigned short int arr[]) { // HERE !!!!!!!!
    const unsigned int arrSize = sizeof(arr)/sizeof(unsigned short int);
    if (arrSize <= 1) {return arr;}

    /*
    Declarations and initializations of the two half array
    */
    const unsigned int arrLeftSize = static_cast<unsigned int>(floor(arrSize/2));
    const unsigned int arrRightSize = static_cast<unsigned int>(arrSize - arrLeftSize);

    unsigned short int arrLeft[arrLeftSize];
    unsigned short int arrRight[arrRightSize];

    for (unsigned int i = 0; i < arrLeftSize; i ++)
        arrLeft[i] = arr[i];
    for (unsigned int i = 0; i < arrRightSize; i ++)
        arrRight[i] = arr[i + arrLeftSize];

    /*
    Sort the two arrays
    */
    for (unsigned int i = 0; i < arrLeftSize; i ++)
        arrLeft[i] = *(sortByFusion(arrLeft) + i);
    for (unsigned int i = 0; i < arrRightSize; i ++)
        arrRight[i] = *(sortByFusion(arrRight) + i);

    /*
    And fusion them
    */
    unsigned int i(0), j(0);
    for (unsigned int k = 0; k < arrSize; k ++) {
        if (i >= arrLeftSize)           {arr[k] = arrRight[j]; j ++;} //That line
        else if (j >= arrRightSize)     {arr[k] = arrLeft[i]; i ++;}  //And that line are here to avoid segmentation fault
        else {
            if (arrLeft[i] <= arrRight[j]) {arr[k] = arrLeft[i]; i ++;}
            else {arr[k] = arrRight[j]; j ++;}
        }
    }
return arr;
}

我做错了什么?我试图把一些ifndef定义为endif,但它没有做更多的事情。似乎每个人都有一个问题,多个定义在这个论坛上总是有点不同。

其次,我使用了一些static_cast,但是当我们传递一个double作为参数时,为什么floor会返回一个double?从逻辑上讲,它应该给我们一个整数(数字的底限总是一个整数......)?

对于编译器,它是GNU GCC,但我不知道如何找到它的版本。我使用Code :: Blocks。

这是头文件:

#ifndef SORT_H_INCLUDED
#define SORT_H_INCLUDED

unsigned short int* sortByFusion(unsigned short int arr[]);

#endif // SORT_H_INCLUDED

1 个答案:

答案 0 :(得分:1)

 const unsigned int arrSize = sizeof(arr)/sizeof(unsigned short int);

这一行没有按预期工作,因为c ++没有保存有关运行时数组的数组长度的任何信息 - 这实际上只是指向数组的指针,因此sizeof(arr)返回{ {1}}这是指针的大小。

为什么第9行出现错误,我无法在没有看到标题sizeof(unsigned short int*)的情况下帮助您。

sort.h
//static_cast<unsigned int>(floor(arrSize/2)); // Wrong
arrSize/2; // Right, C++ does floor integer divisions.

这两行不是有效的C ++,因为在编译时无法确定声明的数组的长度。

相关问题