簡體   English   中英

為什么 push_back() 會改變之前的值?

[英]Why push_back() will change the previous value?

我想通過一個for循環構建一系列帶序號的路徑,所以我使用了一系列的strcpystrcat (我知道有string的方法,但請見諒,我的技術真的很差)。 但是在循環之后,我得到了一系列相同的結果。

這是我的代碼:

#include <iostream>
#include <io.h>
#include <vector>

vector<char*> TempFilePath;    
char temp[300];
strcpy(temp, EndFilepath);
strcat(temp, "\\Temp");
createDirectory(temp);
char TempFilePathChar[300];
for (int j = 0; j < filevector.size(); j++)
{
    int number = j + 1;
    char TEMPNum[1];
    itoa(number, TEMPNum, 10);
    strcpy(TempFilePathChar, temp);
    strcat(TempFilePathChar, "\\tempData");
    strcat(TempFilePathChar, TEMPNum); 
    strcat(TempFilePathChar, ".tif");
    strcpy(TempFilePathChar, TempFilePathChar);
    TempFilePath.push_back(TempFilePathChar);
}

filevector EndFilepath="E:\\" ,文件向量的大小為2。毫無疑問,我想得到流動的結果:

TempFilePath[0]="E:\\Temp\\tempData1.tif"
TempFilePath[1]="E:\\Temp\\tempData2.tif"

但運行后,結果如下:

 TempFilePath[0]="E:\\Temp\\tempData2.tif"
 TempFilePath[1]="E:\\Temp\\tempData2.tif"

有人可以告訴我為什么以及如何改變它嗎?

注意:我還是想用vector<char *>代替vector<string>,因為我在網絡上使用了很多函數,它們的返回值和輸入值都是char *類型。 當然,如果有方法,還是可以達到上述目的的。 再次感謝

您的向量元素都是相同的指針值,即數組TempFilePathChar的地址。 在您的循環中,您將覆蓋該數組的內容,因此您始終獲得循環最后一次迭代產生的內容。

暫無
暫無

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

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