Does pointer arithmetic have uses outside of arrays?

后端 未结 7 2051
青春惊慌失措
青春惊慌失措 2020-12-17 15:00

I think I understand the semantics of pointer arithmetic fairly well, but I only ever see examples when dealing with arrays. Does it have any other uses that can\'t be achie

7条回答
  •  没有蜡笔的小新
    2020-12-17 15:28

    Pointer arithmetic by definition in C happens only on arrays. However, as every object has a representation consisting of an overlaid unsigned char [sizeof object] array, it's also valid to perform pointer arithmetic on this representation. For example:

    struct foo {
        int a, b, c;
    } bar;
    
    /* Equivalent to: bar.c = 1; */
    *(int *)((unsigned char *)&bar + offsetof(struct foo, c)) = 1;
    

    Actually char * would work just as well.

提交回复
热议问题