How to align a pointer in C

后端 未结 5 448
鱼传尺愫
鱼传尺愫 2020-11-29 02:12

Is there a way to align a pointer in C? Suppose I\'m writing data to an array stack (so the pointer goes downward) and I want the next data I write to be 4-aligned so the da

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 02:36

    For some reason I can't use modulo or bitwise operations. In this case:

    void *alignAddress = (void*)((((intptr_t)address + align - 1) / align) * align) ;
    

    For C++:

    template 
    constexpr T padding(T value)
    {
        return ((value + align - 1) / align) * align;
    }
    ...
    char* alignAddress = reinterpret_cast(padding<8>(reinterpret_cast(address)))
    

提交回复
热议问题