SDL_RWread返回具有分段错误的字符串

SDL_RWread return string with segmentation fault

本文关键字:分段 错误 字符串 RWread 返回 SDL      更新时间:2023-10-16

不能使用字符串变量通过SDL_RWwrite/SDL_RWread保存/加载为文件。

// Save data
SDL_RWops* storeDataFile = SDL_RWFromFile("data.bin", "w+b");
if(storeDataFile != NULL) {
string sStoreString = "Hello World";
SDL_RWwrite(storeDataFile, &sStoreString, sStoreString.size(), 1);
SDL_RWclose(storeDataFile);
}
// Load data
SDL_RWops* storeDataFile = SDL_RWFromFile("data.bin", "r+b");
if(storeDataFile != NULL) {
string sStoreString;
SDL_RWread(storeDataFile, &sStoreString, storeDataFile->size(storeDataFile), 1);
SDL_RWclose(storeDataFile);
cout << sStoreString << endl;
}

最后一条 cout 线将给出分段错误。 如果用 int 替换字符串,那么它可以正常工作。

你想要sStoreString.c_str()而不是&sStoreString

否则,您访问的不是字符串内容,而是std::string类的字段。