C - when to use pointer arithmetic, when to use array indexing?

前端 未结 6 1436
盖世英雄少女心
盖世英雄少女心 2020-12-08 11:38

In C, when is it preferrable to use one over the other?

6条回答
  •  醉酒成梦
    2020-12-08 12:38

    It usually depends on the situation. I don't think there's a rule of thumb.

    In some cases, array indexes are better. For example when you have allocated an array

    char* ptr = malloc(SIZE);
    

    and you need the value of ptr to not change, because you want to free it later, then you can work with indexes.

    Or if you get a pointer as a function argument

    void func(char* ptr)
    

    and you need to run over the array, then you can increment the pointer itself and you won't need to create a new variable to use as an index.

    In most cases however, it depends on your own preferences.

提交回复
热议问题