Search code examples
c++charpush-back

Why push_back() will change the previous value?


I want to build a series of paths with serial numbers through a for loop, so I use a series of strcpy and strcat (I know there is a string method, but please forgive me, my technique is really poor). But after the loop, I get a series of the same results.

Here is my code:

#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);
}

The EndFilepath="E:\\", the size of filevector is 2. Undoubtly, I'd like to get the result of flowing:

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

But after running, the result is like following:

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

Can someone tell me why and how to change it?

Note:I still want to use vector < char * > instead of vector < string >, because I use a lot of functions on the network, and their return value and input value are char * type. Of course, if there is a method, it can still achieve the above purpose. Thanks again


Solution

  • Your vector's elements are all the same pointer value, the address of the array TempFilePathChar. In your loop you are overwriting the content of that array so you are always getting the content produced by the last iteration of the loop.