== for pointer comparison

前端 未结 5 1150
终归单人心
终归单人心 2021-01-03 19:35

I quote from \"The C Programming Language\" by Kernighan & Ritchie:

Any pointer can be meaningfully compared for equality or inequality with zero.

5条回答
  •  梦毁少年i
    2021-01-03 19:55

    You cannot use pointer comparison for comparing pointers that point into different arrays.

    So:

    int arr[5] = {1, 2, 3, 4, 5};

    int * p = &arr[0];

    int anotherarr[] = {1, 2};

    int * pf = &anotherarr[0];

    You cannot do if (p == pf) since p and pf do not point into the same array. This will lead to undefined behaviour.

    You can rely on pointer comparison if they point within the same array.

    Not sure about the arithmetic case myself.

提交回复
热议问题