问题描述
我正在使用linux.
I'm using linux.
我有一个像这样的函数
PlayBackgroundIntroMusic((char *)"IntroMusic");
功能是:
void SoundManager::
PlayBackgroundIntroMusic( char * musicFile)
{
// Concatenate extension for each platform
strcat (musicFile,audioExtension);
CCLOG("musicFile: %c" musicFile);
SimpleAudioEngine::sharedEngine()->playBackgroundMusic(std::string(CCFileUtils::fullPathFromRelativePath(musicFile)).c_str(), false);
}
但是我无法在线访问内存:
But i having a bad access to memory on line:
strcat (musicFile,audioExtension);
audioExtension被声明:
audioExtension is declarated:
#include
using std::string;
#include
using std::cout; using std::cerr; using std::endl;
/**
* Declare sound extension for each platform
* Android = ogg
* iOS = caf
* WIN32 = mp3
*/
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
static const char * audioExtension = ".wav";
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
static const char * audioExtension = ".caf";
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
static const char * audioExtension = ".ogg";
#endif
所以,我希望有:
IntroMusic.caf on iOS
IntroMusic.ogg on Android
发生了什么事?
注意:我已经尝试过:
char * musicFileWithExtension = strcat (musicFile,audioExtension);
但是它还是没有用.
musicFile不是常数.如果文件名太长,例如抄送参考示例
musicFile is not a constant. I don't want to declarate a tempchar[80] to avoid overflow if the name of the file is too long like Example cc reference
谢谢.
推荐答案
字符串文字,例如"IntroMusic"
的类型为 const char [N]
可转换为 const char *
.由于语言设计中的错误,它也可以转换为 char *
,但是该转换在C ++中已被正确弃用,因此发出警告.您需要使用动态分配或静态分配的数组,而不是字符串文字.
String literals, such as "IntroMusic"
are of type const char[N]
which is implicitly convertible to const char *
. Through a mistake in language design, it is also convertible to char*
, but that conversion is rightfully deprecated in C++, hence the warning. You need to use an array (dynamically or statically allocated), not a string literal.
或更妙的是,使用 std :: string
.
这篇关于使用strcat对内存的访问错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!