是否将任意整数常量转换为指向对象/函数类型的指针(例如在单元测试中使用)?
struct helper; //opqaue, creation the structure is complicated
struct my_struct{
struct helper *h_ptr;
char another_member;
};
static inline struct my_struct *create_my_struct(struct helper *h_ptr, char am){
struct my_struct *m_ptr = malloc(sizeof(*m_ptr));
m_ptr->h_ptr = h_ptr;
m_ptr->another_member = am;
return m_ptr;
}
我想为它编写如下单元测试:
uintptr_t helper_ptr = (uintptr_t) 2; //How about this?
char am = 'a';
struct my_struct *ms_ptr = create_my_struct((struct helper *) helper_ptr, am);
//do asserts
我不确定的是(struct helper *) helper_ptr
。是UB吗?如果 (uintptr_t) 2
没有正确对齐怎么办?
最佳答案
来自 C11 标准 6.3.2.3 指针,第 5 段:
An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
所以只要你不取消引用就可以这样做,而且它不是 UB,但无论发生什么都取决于平台。
关于将整数常量转换为指针类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764405/