2015-04-16 124 views
1

我目前開始與c和allegro5一起工作。我想把我的初始化代碼放到一個init()方法中,但是我正在努力將指針返回到ALLEGRO_EVENT_QUEUE和ALLEGRO_DISPLAY。儘管指針在函數中被初始化,但它們在之後仍爲NULL;我認爲分配給指針的值將在當前範圍的末尾存活,因爲底層值被修改,但內存地址保持不變。 這裏是我的代碼:C通過指針返回結構體

#include <stdio.h> 
#include <allegro5/allegro.h> 

void init(ALLEGRO_DISPLAY *display_ptr, ALLEGRO_EVENT_QUEUE *queue_ptr) { 
    al_init(); 
    al_install_keyboard(); 
    display_ptr = al_create_display(640, 480); 
    queue_ptr = al_create_event_queue(); 
    al_register_event_source(queue_ptr, al_get_display_event_source(display_ptr)); 

    al_clear_to_color(al_map_rgb(0,0,0)); 

    al_flip_display(); 
} 

int main(int argc, char **argv){ 

    ALLEGRO_DISPLAY *display = NULL; 
    ALLEGRO_EVENT_QUEUE *event_queue = NULL; 

    init(display, event_queue); 
    printf("%d\n", display == NULL); //prints out 1 
    printf("%d\n", event_queue == NULL); //prints out 1 

    //Further code 

    return 0; 
} 

任何提示或幫助是極大的讚賞。

回答

3

您需要傳遞指針本身的地址。

嘗試像這樣

void init(ALLEGRO_DISPLAY **display_ptr, ALLEGRO_EVENT_QUEUE **queue_ptr) { 
    al_init(); 
    al_install_keyboard(); 
    *display_ptr = al_create_display(640, 480); 
    *queue_ptr = al_create_event_queue(); 
    /* I assume you are guaranteed to not recieve `NULL's or why don't you check ? */ 
    al_register_event_source(*queue_ptr, al_get_display_event_source(*display_ptr)); 

    al_clear_to_color(al_map_rgb(0,0,0)); 

    al_flip_display(); 
} 

init(&display, &event_queue); 

記住,在C你總是按值傳遞,所以傳遞的指針被複制,而它們包含它們存儲在同一地址不同的地方,因此改變其中一個,不影響另一個。

將地址傳遞給指針,可以修改存儲在指針中的地址。

如果你想檢查我說的是真的,試着在每個函數中打印指針的地址,你會發現它們是不同的。

+0

耶!有用!非常感謝你。 –

+1

只要你能夠接受答案。 –

1

參數按值調用,即在您的情況下不返回指針地址。

要解決,你需要傳遞的指針的指針這樣的:

#include <stdio.h> 
#include <allegro5/allegro.h> 

void init(ALLEGRO_DISPLAY **display_ptr, ALLEGRO_EVENT_QUEUE **queue_ptr) { 
    al_init(); 
    al_install_keyboard(); 
    *display_ptr = al_create_display(640, 480); 
    *queue_ptr = al_create_event_queue(); 
    al_register_event_source(*queue_ptr, al_get_display_event_source(*display_ptr)); 

    al_clear_to_color(al_map_rgb(0,0,0)); 

    al_flip_display(); 
} 

int main(int argc, char **argv){ 

    ALLEGRO_DISPLAY *display = NULL; 
    ALLEGRO_EVENT_QUEUE *event_queue = NULL; 

    init(&display, &event_queue); 
    printf("%d\n", display == NULL); //prints out 1 
    printf("%d\n", event_queue == NULL); //prints out 1 

    //Further code 

    return 0; 
} 
+1

不要變通,這是正確的方法。 –

+0

這是有爭議的。這是一種解決方法,不需要通過引用進行呼叫,例如, C++。 – Meixner

+1

你的意思是c比較低劣,因爲它不會讓你的生活更難以通過參照傳遞?在我看來,通過引用是令人困惑的,因爲你可以忘記所傳遞的變量將被修改,所以通過引用傳遞是C++中的醜陋之處之一,並且它曾經耗費我很多錢。 –