gpt4 book ai didi

c++ - 字符数组末尾的额外字符 (char *Result = new char) 8OI

转载 作者:太空宇宙 更新时间:2023-11-04 15:52:03 25 4
gpt4 key购买 nike

我有一个 C++ 函数,它将 LPSTR 类型变量拆分为一个字符数组 (char*) 示例:

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"

这是我要编写的函数:

int FindTextLength(char* Text){
int length

h=0; 对于(int i = 0;我

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(
}

实际上它并没有那么糟糕。问题是当我声明一个 char 数组(char *Result = new char;)时,它并不知道我在最终结果(结果)如果您有任何想法或建议,请告诉我,我真的被困在这里。感谢您的任何建议和回复。

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

最佳答案

char *Result = new char[PathLength+FileLength];

Result 指向的数据应以终止字符 \0 结尾。或者,当返回 Result 指向的字符串时,您会遇到问题。所以,

Result[PathLength+FileLength-1] = '\0' ;

确保您永远不会溢出缓冲区,或者更好的选择是使用 std::string

关于c++ - 字符数组末尾的额外字符 (char *Result = new char) 8OI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6300331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com