2016-11-29 183 views
2

我需要一些幫助來理解這種結構:需要幫助瞭解結構用C

typedef struct std_fifo{ 
    char* name; 
    struct std_fifo* next; 
}std_fifo, *fifo; 

隨着typedef我知道,我可以用我的代碼編寫struct std_fifostd_fifo代替。但是*fifo呢?

+0

這意味着您可以使用'fifo variablename;'而不是'struct std_fifo * variablename;'或'std_fifo * variablename;'來聲明指向結構體的指針。 – mch

+0

所以我可以寫'fifo variablename;'或'std_fifo * variablename;' ?它是一樣的嗎? – iAmoric

+6

請參閱[是否是一個好主意typedef指針](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) - 簡潔的答案:No. –

回答

3

代碼

typedef struct std_fifo{ 
    char* name; 
    struct std_fifo* next; 
}std_fifo, *fifo; 

創建兩個(非常嚴重命名)typedef名稱,std_fifofifo

typedef名std_fifo相當於類型struct std_fifo,並且可以代替struct std_fifo使用:

std_fifo fifo_instance;  // creates an instance of struct std_fifo 
std_fifo get_fifo();   // declares get_fifo as a function returning an 
          // instance of struct std_fifo 
void read_fifo(std_fifo *);// declares a function taking parameter of type 
          // pointer to struct std_fifo 

typedef名fifo相當於類型struct std_fifo *,並且可以代替struct std_fifo *使用:

fifo fifo_ptr;    // creates a pointer to an instance of struct std_fifo 
fifo get_fifoptr();   // declares get_fifoptr as a function returning a pointer 
          // to an instance of struct std_fifo 
void read_fifo(fifo);  // declares a function taking a parameter of type 
          // struct std_fifo * 

的原因代碼像

typdef struct std_fifo { ... } std_fifo; 

作品是因爲C有四個不同的名字空間標識符:標籤,標籤名稱,structunion成員名稱,以及其他一切。 標籤名稱std_fifo總是在struct關鍵字之前,這是編譯器將其與std_fifo typedef名稱區分開來的方式。

使用的typedef幾點建議:

雖然它們可以幫助你的代碼掃描更好的在某些情況下,使用的typedef實際上可以掩蓋你的意圖,使各類更難使用。如果類型的用戶必須知道其表示(例如訪問struct的成員,或取消引用指針類型,或者在printfscanf調用中使用正確的轉換說明符,或者調用函數propertyly等),那麼你應該而不是隱藏在一個typedef後面的表示。

如果您決定使用想要隱藏typedef後面的類型表示,那麼您還應該爲涉及該類型的任何操作提供完整的API。 C使用FILE類型執行此操作;不是直接操縱對象,而是將指針傳遞給各個例程。所以,如果你決定要隱藏struct std_fifo * typedef名fifo後面,那麼你也應該創建一個API,如:

fifo new_fifo();    // create a new fifo queue 
void destroy_fifo(fifo *); // destroy an existing fifo queue 
set_name(fifo, const char *); // set the name of a fifo element 
char *get_name(fifo);   // retrieve the name of a fifo element 
fifo push_fifo(fifo);   // add an element to the end of the queue 
fifo pop_fifo(fifo);   // remove an element from the front of the queue 

抽象可以是一件好事,但「漏」抽象是比沒有抽象的更糟所有。

1

這是一個結構的有效定義,可以給一個名稱和一個指針。

typedef struct std_fifo{ 
    char* name; 
    struct std_fifo* next; 
}std_fifo, *fifo; 

在這個代碼,其中std_fifo是一個結構和*fifo是指針這個結構。

我強烈建議你看看這裏:http://www.cplusplus.com/forum/windows/57382/

+0

請注意,'std_fifo'是結構類型的類型名稱的別名,'fifo'是指向相同結構類型的指針類型的別名。你的評論使它看起來有點像你認爲它們是變量。如果你用'static'或'extern'替換了存儲類'typedef',那麼片段確實會定義或聲明一對變量。使用'typedef'的'存儲類',它定義了'struct std_fifo'類型的別名。 –

+0

是的,我已經告訴它,它是一個**結構**。我沒有說它是結構變量名稱或任何其他事物的名稱?好的。@JonathanLeffler – Prometheus

+0

好的。我會把它留在「我發現你的語言不明確」,但你知道你的意思。 –