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)
好吧,对于初学者你有output[1]和output[2].数组在c/c ++中是零索引的,因此它们应该是: output[0]和output[1].
但是,既然你问的是c ++ ......我劝你用std::vector或者std::pair.
(当然,为了便于阅读,您可能只想使用具有有用字段名称的简单结构)
我知道我在某个地方犯了一个愚蠢的错误,有人可以为我指出它
当然,它与Q的主题无关:
output[2] = unsigned int(inputFrac * 2e32);
Run Code Online (Sandbox Code Playgroud)
在正确的条目output是[0]和[1]-你索引出界."未定义的行为"结果(例如,您观察到的崩溃).