在C++中返回动态数组

Elp*_*rto 0 c++ arrays function dynamic

我需要从函数返回unsigned int*.下面的代码将编译但在运行时将在Windows 64位计算机上崩溃.我知道我在某个地方犯了一个愚蠢的错误,有人可以为我指出它.:P.我也在我的标题中声明了这个函数,所以我知道它不是那个错误.

请注意我已经审查了变量名和数字,因为此函数所在的问题尚未公开发布.

功能:

 unsigned int* convertTime(unsigned int inputInteger, unsigned short inputFrac) {
    unsigned int* output = new unsigned int[2];
    double messageTimeFraction = double(inputFrac) * 20e-6;

    output[1] = unsigned int(inputInteger + 2209032000);
    output[2] = unsigned int(messageTimeFraction * 2e32);

    return output; // Seconds
}
Run Code Online (Sandbox Code Playgroud)

执行:

unsigned int* timeStamp;
timeStamp = convertTime(inputInteger,inputFrac);
Run Code Online (Sandbox Code Playgroud)

Ste*_*hen 8

好吧,对于初学者你有output[1]output[2].数组在c/c ++中是零索引的,因此它们应该是: output[0]output[1].

但是,既然你问的是c ++ ......我劝你用std::vector或者std::pair.

(当然,为了便于阅读,您可能只想使用具有有用字段名称的简单结构)

  • @Pete:在使用动态数组的地方,`std :: vector`比_always_好得多.如果`std :: vector`不合适(实际上,这可能是一个带有两个成员的`struct`),那么动态数组也是如此.所以你应该评论_question_.在这个答案中,你的投票是不公平的,没有理由. (4认同)

Ale*_*lli 6

我知道我在某个地方犯了一个愚蠢的错误,有人可以为我指出它

当然,它与Q的主题无关:

output[2] = unsigned int(inputFrac * 2e32);
Run Code Online (Sandbox Code Playgroud)

在正确的条目output[0][1]-你索引出界."未定义的行为"结果(例如,您观察到的崩溃).