簡體   English   中英

在C ++中返回動態數組

[英]Return dynamic array in C++

我需要從函數返回一個無符號的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);

好吧,對於初學者來說,您具有output[1]output[2] 數組在c / c ++中為零索引,因此應為: output[0]output[1]

但是,由於您正在詢問c ++ ...我建議您使用std::vectorstd::pair

(當然,出於可讀性考慮,您可能只想使用帶有有用字段名稱的簡單結構)

我知道我在某個地方犯了一個愚蠢的錯誤,有人可以為我指出

當然,這與Q的主題無關:

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

output中正確的輸入是[0][1] -您的索引超出范圍。 結果為“未定義的行為”(例如,您觀察到的崩潰)。

2個元素的數組中的索引是array [0]和array [1],因此將其更改為:

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

C ++中的數組基於零,因此大小為2的數組的元素為output[0]output[1]

您可能還想返回一些更好地表示您要返回的數據的內容,例如具有seconds和fractional_seconds成員的結構,而不是創建新的數組。

您在做什么也有些奇怪-2209032000是70年的秒數,而將short乘以2e32的結果將溢出unsigned int的大小。

使用output[0]output[1] ,C / C ++數組基於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);

我為各種格式創建了一個時間結構,並編寫了轉換器函數來處理轉換。 通過使用結構,我不必擔心內存泄漏和提高的可讀性。 此外,與使用動態數組相比,該代碼現在具有更大的可伸縮性,因為我可以添加更多字段並創建新的時間格式。

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

我的愚蠢錯誤是基於零的索引的錯字,但更大的錯誤是使用動態數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM