2015-05-13 190 views
-2

我對結構中的指針感到非常困惑。 我有一段代碼,這一點我沒有完全理解的是, 代碼:結構指針

typedef struct{ 
    int fildes // basic file descriptor 
    char* location // location would be somewhere in /dev/tty* 
}context0; // structure named 'context' containing the 2 elements above. 

context0 someContext; // create a context struct 

process(&readLocation); // takes reference from the function 'readlocation' 
// i do not know what this process function does. 

uint_16_t readLocation(int8_t *buffer, int16_t n, SomeContext){ // buffer pointer, n size read, and fidles 
context0 foo = *(context0*) SomeContext; // ???? What Is Going ON right here ???? 
return read(foo.fd, buffer, n); 
} 

我已經更改了名字,但它的代碼,我不完全理解的。

一些問題:

  • 因爲readLocation功能作爲引用傳遞它應該不能被定義爲void*?面前的uint_32_t

  • 主要問題:context0 foo = * (context0*) SomeContext;做什麼?

+1

這不是C++代碼的一個有效一塊分。 'SomeContext'應該是一個類型或變量。如果它是一個變量,什麼是ts類型? –

+0

someContext是一個context0類型的結構,如果anotherContext被添加someContext可以被看作是串行輸入的上下文,而另一個上下文將是串行輸出,其中將被寫入 – iBeyondPower

+0

否則:問題1:否,任何類型的函數都可以作爲參數傳遞。問題2:它看起來像指向類型'context0 *'的轉換,並且是一個解引用。 (但正如我所說,這不是一個有效的代碼。) –

回答

0

好吧,看起來(context0 *)實際上是一個類型轉換,它由(int)bar將其他類型設置爲'int'類型。這是爲了將變量欄設置爲上下文的類型。

這個類型轉換也可以通過指針類型強制轉換來完成(int *)或(struct name *),或者在這種情況下(context0 *)。

最後,parenthisis之外的指針取消引用結構指針,以訪問它指向的任何內容,並將這些信息放在struct context0 foo中。

爲什麼這是nessesary我不知道,但語法指向這一點。

感謝,哦烏爾歡迎NP

,並感謝ü的Gabor Angyal,但不能給任何一級