字符数组末尾的额外字符(字符*结果=新字符)8OI
|
我有一个C ++函数,将LPSTR类型变量拆分为一个char数组(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;
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(
}
实际上,它并没有那么糟糕。问题是当我声明一个char数组(char * Result = new char;)时,它并没有确定长度是多少,我在最终结果的末尾附加了一个额外的字符(结果)
如果您有任何想法或建议,请告诉我,我真的很困在这里。
感谢您的任何建议和回应。
Solusion在最后添加
功能:
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;
}
没有找到相关结果
已邀请:
4 个回复
绵扇寸访
指向的数据应以终止字符
结尾。否则,当返回由
指向的字符串时,您将遇到问题。所以,
确保您不会溢出缓冲区,或者甚至更好的选择是使用
。
瓜唱鬼
进行,其中N是数组的大小(例如
)
峨躬坎抬焚
那应该崩溃。您正在分配1个字符的缓冲区,然后尝试strcpy进入它们,这显然会很快使这些缓冲区溢出。另外,请记住,在字符串中的字符之后,您需要为空终止符多留1个空格。
郸身
。 如果您不这样做,则对于字符串长度,会有诸如strlen / wcslen之类的函数。 Windows Shell还具有一些非常方便的路径操作功能,网址为http://msdn.microsoft.com/zh-cn/library/bb773559%28v=vs.85%29.aspx 它们中的大多数可以派上用场,通常您可以操纵静态长度
缓冲区。 请记住,最大路径为256左右,对于更深层的嵌套文件夹,存在一些问题。