c# 关于C,SDL2和指针的基本问题[重复]

roejwanj  于 2023-06-04  发布在  C#
关注(0)|答案(1)|浏览(256)

此问题已在此处有答案

How do I modify a pointer that has been passed into a function in C?(7个回答)
3分钟前关闭
我想用C语言学习SDL 2。我的问题是,我试图通过这样做来避免创建全局SDL_Window:

void init(SDL_Window *win){
SDL_Init(SDL_INIT_EVERETHING);
    win = SDL_CreateWindow("PONG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
}

int main(){
    SDL_Window *window = NULL;
    init(window);
    if(window == NULL) printf("error!");
    
    return 0;
}

问题是窗口只在init函数调用中“存在”,程序仍然打印“error!“,指示main函数中的窗口仍然是空指针。
如果我直接在main中这样做,它会像预期的那样工作(不打印“错误!“):

int main(){
    SDL_Window *window = NULL;
  
    SDL_Init(SDL_INIT_EVERETHING);
    window = SDL_CreateWindow("PONG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
    if(window == NULL) printf("error!");
    
    return 0;
}

先谢谢你了。

bqujaahr

bqujaahr1#

C实现了按值调用,所以如果你传递一个变量,实际上只传递它们的值。你可以通过传递一个指向你想要改变的变量的指针来创建一个“out”变量。

void init(SDL_Window ** win){
SDL_Init(SDL_INIT_EVERETHING);
    *win = SDL_CreateWindow("PONG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
}

int main(){
    SDL_Window *window = NULL;
    init(&window);
    if(window == NULL) printf("error!");
    
    return 0;
}

或者您只是返回所需的信息:

SDL_Window *win init(){
SDL_Init(SDL_INIT_EVERETHING);
    return SDL_CreateWindow("PONG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
}

int main(){
    SDL_Window *window = NULL;
    window = init();
    if(window == NULL) printf("error!");
    
    return 0;
}

相关问题