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

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

    Pointer arithmetic may look fancy and "hackerish", but I have never encountered a case it was FASTER than the standard indexing. Just the opposite, I often encountered cases when it slowed the code down by a large factor.

    For example, typical sequential looping through an array with a pointer may be less efficient than looping with a classic index on a modern processors, that support SSE extensions. Pointer arithmetic in a loop sufficiently blocks compilers from performing loop vectorization, which can yield typical 2x-4x performance boost. Additionally, using pointers instead of simple integer variables may result in needless memory store operations due to pointer aliasing.

    So, generally pointer arithmetic instead of standard indexed access should NEVER be recommended.

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

    Something fun I hope you never have to deal with: pointers can alias, whereas arrays cannot. Aliasing can cause all sorts of non-ideal code generation, the most common of which is using a pointer as an out parameter to another function. Basically, the compiler cannot assume that the pointer used by the function doesn't alias itself or anything else in that stack frame, so it has to reload the value from the pointer every time it's used. Or rather, to be safe it does.

    0 讨论(0)
  • 2020-12-30 10:11
    char *my_strcpy(const char *s, char *t) {
      char *u = t;
      while (*t++ = *s++);
      return u;
    }
    

    Why would you want to spoil such a beauty with an index? (See K&R, and how they build on up to this style.)There is a reason I used the above signature the way it is. Stop editing without asking for a clarification first. For those who think they know, look up the present signature -- you missed a few restrict qualifications.

    Structure alignment testing and the offsetof macro implementation.

    0 讨论(0)
  • 2020-12-30 10:13
    #include ctype.h
    void skip_spaces( const char **ppsz )
    {
      const char *psz = *ppsz;
      while( isspace(*psz) )
        psz++;
      *ppsz = psz;
    }
    
    void fn(void)
    {
      char a[]="  Hello World!";
      const char *psz = a;
      skip_spaces( &psz );
      printf("\n%s", psz);
    }
    
    0 讨论(0)
  • 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.

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

    Often the choice is just one of style - one looks or feels more natural than the other for a particular case.

    There is also the argument that using indexes can cause the compiler to have to repeatedly recalculate offsets inside a loop - I'm not sure how often this is the case (other than in non-optimized builds), but I imagine it happens, but it's probably rarely a problem.

    One area that I think is important in the long run (which might not apply to an introductory C class - but learn 'em early, I say) is that using pointer arithmetic applies to the idioms used in the C++ STL. If you get them to understand pointer arithmetic and use it, then when they move on to the STL, they'll have a leg up on how to properly use iterators.

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