2016-05-13 78 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

但不要返回堆栈指针。它不会做你打算做的事情。 –