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

标签 c pointers struct

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

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/

相关文章:

c - 错误 : "invalid use of incomplete type ‘RSA {aka struct rsa_st}" in OpenSSL 1. 1.0

c - 在 C 中从字符串转换为整数时出现内存泄漏(?)

c - waitpid() 不允许将 SIGINT 发送到子进程?

c++ - *&var 是多余的吗?

c++ - 为什么这个 sizeof 运算符会出错?

c# - 如何为 P/Invoke 声明指向结构的指针?

C 语言 - 根据方阵边的平方数读取方阵的通用算法?

c++ - 链表内存读取错误

调用memset导致segmentation fault

c++ - push_back(move(struct.unique_ptr)) 导致编译错误