SDL_RWread return 字符串存在分段错误

SDL_RWread return string with segmentation fault

SDL_RWwrite/SDL_RWread.

无法使用字符串变量 save/load 作为文件
// 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;
}

最后一行会给出分段错误。 如果将字符串替换为 int,则可以正常工作。

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

否则您访问的不是字符串内容,而是 std::string class.

的字段