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

前端 未结 9 577
没有蜡笔的小新
没有蜡笔的小新 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:24

    You're asking about C specifically, but C++ builds upon this as well:

    Most pointer arithmetic naturally generalizes to the Forward Iterator concept. Walking through memory with *p++ can be used for any sequenced container (linked list, skip list, vector, binary tree, B tree, etc), thanks to operator overloading.

    0 讨论(0)
  • 2020-12-30 10:28

    iterating through a 2-dimensional array where the position of a datum does not really matter
    if you dont use pointers, you would have to keep track of two subscripts
    with pointers, you could point to the top of your array, and with a single loop, zip through the whole thing

    0 讨论(0)
  • 2020-12-30 10:29

    If you were using an old compiler, or some kind of specialist embedded systems compiler, there might be slight performance differences, but most modern compilers would probably optimize these (tiny) differences out.

    The following article might be something you could draw on - depends on the level of your students:

    http://geeks.netindonesia.net/blogs/risman/archive/2007/06/25/Pointer-Arithmetic-and-Array-Indexing.aspx

    0 讨论(0)
提交回复
热议问题