2016-05-13 77 views
0

假設我有以下代碼:存儲結構對象的空指針

struct inst { 
    uint32_t field1; 
    uint16_t field2; 
    void *priv; 
}; 

struct ops { 
    int (*init)(void); 
    int (*deinit)(void); 
    int (*run)(void); 
}; 

因此我可以這樣做:

struct inst p1; 
struct ops ops; 

/* init p1 and ops.*/ 
... 

inst->priv = ops; 

它是安全的這樣以後訪問priv數據:

return (struct ops *)inst->priv 

回答

0
inst->priv = ops; 

是不是應該

inst->priv = &ops; 

此外,去你的問題,「是否安全這樣以後訪問私法中的數據:」不,沒有。它取決於你在哪裏創建結構實例。如果您要創建這樣

struct ops * dummyA() 
{ 
    struct inst p1; 
    struct ops ops; 
    //(...) 
    inst->priv = (void*)&ops; 
    //(...) 
    return (struct ops *)inst->priv; 
} 

,因爲那裏的功能,因此,它們的內存地址將被標記爲空閒直接在堆棧中創建這些結構,當你離開的功能,它是不是安全。

一種方法來解決這個問題是使用堆(malloc的)或(也許是更簡單的方法)聲明的結構是這樣的:

static struct inst p1; 
static struct ops ops; 

這樣你就不需要擔心內存分配並且您確定這些堆棧元素將永遠不會被擦除,直到程序結束,因此您可以根據需要使用它們的指針。

+0

感謝您的意見。我知道關於返回堆棧分配對象的問題,而我的問題是關於'返回(struct ops *)inst-> priv'中的類型轉換 - 是需要還是可以省略? – Mark

+0

你可以省略它。 –

+0

但不要返回堆棧指針。它不會做你打算做的事情。 –