What are convincing examples where pointer arithmetic is preferable to array subscripting?

前端 未结 9 657
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 09:23

I\'m preparing some slides for an introductory C class, and I\'m trying to present good examples (and motivation) for using pointer arithmetic over array subscripting.

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 10:17

    Getting a pointer again instead of a value:

    One usually uses pointer arithmetic when they want to get a pointer again. To get a pointer while using an array index: you are 1) calculating the pointer offset, then 2) getting the value at that memory location, then 3) you have to use & to get the address again. That's more typing and less clean syntax.

    Example 1: Let's say you need a pointer to the 512th byte in a buffer

    char buffer[1024]
    char *p = buffer + 512;
    

    Is cleaner than:

    char buffer[1024];
    char *p = &buffer[512];
    

    Example 2: More efficient strcat

    char buffer[1024];
    strcpy(buffer, "hello ");
    strcpy(buffer + 6, "world!");
    

    This is cleaner than:

    char buffer[1024];
    strcpy(buffer, "hello ");
    strcpy(&buffer[6], "world!");
    

    Using pointer arithmetic ++ as an iterator:

    Incrementing pointers with ++, and decrementing with -- is useful when iterating over each element in an array of elements. It is cleaner than using a separate variable used to keep track of the offset.


    Pointer subtraction:

    You can use pointer subtraction with pointer arithmetic. This can be useful in some cases to get the element before the one you are pointing to. It can be done with array subscripts too, but it looks really bad and confusing. Especially to a python programmer where a negative subscript is given to index something from the end of the list.

提交回复
热议问题