我目前正在重新进入C语言编写一个小游戏 . 我正在使用Visual Studio 2017和SDL2 . 我正在按照一系列教程进入SDL . 我的问题似乎与我没有完全理解c中指针的工作方式有关 . 我传递一个指向函数的指针作为参数,并希望在此函数中使用它作为另一个函数的参数,该函数返回指向SDL_Surface的指针 . 遵循我的代码:

init SDL:

SDL_Surface* init(SDL_Window *window)
{
  SDL_Surface *screenSurface = nullptr;
  if (SDL_Init(SDL_INIT_VIDEO) < 0)
  {
    printf("%s", "Error in init");    
  }
  else
  {   
    screenSurface = SDL_GetWindowSurface(window);
  }

  return screenSurface;
}

加载bmp:

SDL_Surface* loadMedia(const char file[])
{
  SDL_Surface *image = SDL_LoadBMP(file);
  if (image == nullptr)
  {
    printf("%s", "Error in loadMedia");
  }
  return image;
}

主要:

int main(int argc, char *argv[])
{
  SDL_Window *window = SDL_CreateWindow("xyz", SDL_WINDOWPOS_UNDEFINED, 
  SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

  SDL_Surface *screenSurface = init(window);
  if (screenSurface == nullptr)
  {
    printf("%s", "surface is null");
  }

  SDL_Surface *image = loadMedia("resources/images/village.bmp");
  SDL_BlitSurface(image, NULL, screenSurface, NULL);

  SDL_UpdateWindowSurface(window);
  SDL_Delay(1000);

  SDL_FreeSurface(image);
  image = nullptr;
  SDL_DestroyWindow(window);
  window = nullptr;
  SDL_Quit();

  return 0;
}

如果我创造

SDL_Window *window = SDL_CreateWindow("xyz",...)

作为一个全局变量并在init()中初始化它,一切正常,screenSurface用有效值初始化 . 只要我在代码中执行操作,将指针窗口传递给init()以在那里创建表面然后返回screenSurface,screenSurface = SDL_GetWindowSurface(window)返回null .

我在过去的几年里一直在编写SAS和Java编程,几年没碰到c,所以我确定它只是我身边的一个小误会,但我无法弄清楚它是什么 .

Thx提前:)