I have a C++ function that splits LPSTR type variable an attact it into an char array (char*)
Example:
this->XMeshTexturePath = FindTexturePath(XMeshTexturePath,d3dxMaterials[i].pTextureFilename);
//the value of XMeshTexturePath is: Models\\Textures\\
//the value of d3dxMaterials[i].pTextureFilename is: BlaBlaBla\\BlaBla\\Cyrex.x
//The Result(XMeshTexturePath) should be like this:"Models\\Textures\\Cyrex.x"
This is the funcion I’m trying to write:
int FindTextLength(char* Text){
int length
h=0;
for(int i=0;i
char* FindTexturePath( char* TexturePath ,LPSTR FileNameToCombine){
int FileLength=0;
int PathAndFileLength=0;
char *FileName = new char;
char *TexPathAndName = new char;
strcpy(TexPathAndName, FileNameToCombine);
PathAndFileLength = FindTextLength(TexPathAndName);
for(int i=0; i<PathAndFileLength; i++){
if( TexPathAndName[i] != NULL){
if(TexPathAndName[i] != '\\'){
FileName[FileLength] = TexPathAndName[i];
FileLength++;
}
else
FileLength = 0 ;
}else break;
}
int PathLength = FindTextLength(TexturePath);
char *Result = new char;
//==============>> // I also tryed this:char *Result = new char[PathLength+FileLength];
//==============>> // char *Result = new char();
for(int i=0; i<PathLength; i++){
if( TexturePath[0] != NULL){
Result[i] = TexturePath[i];
}
else break;
}
for(int i=0; i<FileLength; i++){
if( FileName[0] != NULL){
Result[PathLength + i] = FileName[i];
}
else break;
}
return **Result**; // The Problem is here It should be like this:
// "Models\\Textures\\Cyrex.x"
// But I'm taking one of these as result:
// "Models\\Textures\\Cyrex.x{"
// "Models\\Textures\\Cyrex.xu"
// "Models\\Textures\\Cyrex.xY"
// The last character is random... 8O(
}
Actualy it’s not wokring so bad. The problem is when I declare an char array(char *Result = new char;) it does’not metter how much is length I’m takin an extra character at the end of final result(Result)
I’m realy stucked in here if you have any idea or suggestion plase let me know.
Thanks for any advice and respons.
The Solusion is adding this at the end
of function:
Result[i] = TexturePath[i];
}
else break;
}
for(int i=0; i<FileLength; i++){
if( FileName[0] != NULL){
Result[PathLength + i] = FileName[i];
}
else break;
}
Result[PathLength+FileLength] = '\0' ; // This part is resloving the problem.
// **Thanks for helps**.
return Result;
}
Resultpointed data should end with the termination character\0. Or you will run into problems when returned such a string pointed byResult. So,Make sure you never overrun the buffer or even a better option is to use
std::string.