gpt4 book ai didi

将整数常量转换为指针类型

转载 作者:太空狗 更新时间:2023-10-29 16:00:14 25 4
gpt4 key购买 nike

是否将任意整数常量转换为指向对象/函数类型的指针(例如在单元测试中使用)?

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com