在C ++中返回动态数组

时间:2010-06-23 15:40:11

标签: 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
}

实现:

unsigned int* timeStamp;
timeStamp = convertTime(inputInteger,inputFrac);

7 个答案:

答案 0 :(得分:8)

嗯,对于初学者,你有output[1]output[2]。数组在c / c ++中为零索引,因此它们应为:output[0]output[1]

但是,既然你问的是c ++ ......我建议你使用std::vectorstd::pair

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

答案 1 :(得分:6)

  

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

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

output[2] = unsigned int(inputFrac * 2e32);

output中的正确条目为[0][1] - 您的索引超出范围。 “未定义的行为”结果(例如,您观察到的崩溃)。

答案 2 :(得分:0)

2个元素数组中的索引是array [0]和array [1],因此将其更改为:

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

答案 3 :(得分:0)

C ++中的数组是基于零的,因此大小为2的数组元素为output[0]output[1]

您可能还想返回更能代表您返回的数据的内容,例如包含seconds和fractional_seconds成员的结构,而不是创建新数组。

你正在做的事情也有些奇怪 - 2209032000是70年来的秒数,短路乘以2e32的结果将超出unsigned int的大小。

答案 4 :(得分:0)

使用output[0]output[1],C / C ++数组是基于0的

答案 5 :(得分:0)

在C风格中编写这样的函数的更常用方法是将引用传递给将要设置的变量。

为方便起见,您返回输出缓冲区,以便可以在表达式中轻松使用该函数。

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

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

  return output; // Seconds
}

// later
unsigned int seconds[2];
unsigned int* pseconds;
pseconds = convertTime(seconds,a,b);

答案 6 :(得分:0)

我为各种格式创建了一个时间结构,并编写了转换器函数来处理转换。通过使用结构,我不必担心内存泄漏和提高可读性。此外,代码现在比使用动态数组更具可扩展性,因为我可以添加更多字段并创建新的时间格式。

struct time{
    unsigned int timeInteger;
    unsigned int timeFraction;
}time_X, time_Y;

我的愚蠢错误是基于零的索引的错误,但更大的错误是使用动态数组。