【发布时间】:2013-01-23 21:10:14
【问题描述】:
以下是我的示例代码。它只是一个示例,类似于我在应用程序中使用的代码。
#define STR_SIZE 32
void someThirdPartyFunc(const char* someStr);
void getString(int Num, const char* myStr)
{
char tempStr[] = "MyTempString=";
int size = strlen(tempStr) + 2;
snprintf((char*)myStr, size, "%s%d", tempStr, Num);
}
int main()
{
const char * myStr = new char(STR_SIZE);
getString(1, myStr); // get the formated string by sending the number
someThirdPartyFunc(myStr); // send the string to the thirdpartyFunction
delete myStr;
return 0;
}
如果我使用此代码,我会遇到异常。我认为问题在于删除“myStr”。但是删除确实很有必要。
还有其他方法可以格式化 getString 中的字符串并将其发送到 ThirdPartyFunc 吗?
提前致谢。
【问题讨论】:
-
我不确定你在做什么,但为什么不改用
std::string? -
你能解释一下,为什么
+ 2在strlen(tempStr) + 2中? -
你为什么要把
myStr当作const char*,然后在函数中强制转换常量? -
谢谢。我不能使用 std::string :(.