How to align a pointer in C

后端 未结 5 431
鱼传尺愫
鱼传尺愫 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:43

    Based on tricks learned elsewhere and one from reading @par answer apparently all I needed for my special case which is for a 32-bit like machine is ((size - 1) | 3) + 1 which acts like this and thought might be useful for other,

    for (size_t size = 0; size < 20; ++size) printf("%d\n", ((size - 1) | 3) + 1);
    
    0
    4
    4
    4
    4
    8
    8
    8
    8
    12
    12
    12
    12
    16
    16
    16
    16
    20
    20
    20
    

提交回复
热议问题