C语言的指针不能与数组之前的内存进行比较(The pointer of C language cannot be compared with the memory before the array)

标准允许指向数组元素的指针与指向数组最后一个元素后面的那个内存位置的指针进行比较,但是不允许与指向数组第一个元素之前的那个内存位置的指针进行比较。

  • 案例一#define DATAMAX 5
    int values[DATAMAX]
    int *cp
    // 这个测试是没问有题的
    for(cp = &values[0]; cp < &values[DATAMAX]; ) { *cp++ = 0 } 注意:此案例是通过指针与数组最后一个元素之后的那个内训进行比较,所以运行是没问题的
  • 案例二#define DATAMAX 5
    int values[DATAMAX]
    int *cp
    // 这个测试在有的编译上是无法运行的
    for(cp = &values[DATAMAX-1]; cp >= &values[0]; cp–)
    {
    *cp = 0
    }

    注意:此案例是通过指针与数组第一个元素之前的内存进行比较,在大多数C编译器中是没问题的,对部分编译器是无法正常运行的。对于负责
    移植代码的程序员简直是个噩梦

————————

The standard allows a pointer to an array element to be compared with a pointer to the memory location after the last element of the array, but does not allow a pointer to the memory location before the first element of the array.

  • Case 1 #define datamax five
    int values[DATAMAX]
    int *cp
    //There are no questions in this test
    for(cp = &values[0]; cp < &values[DATAMAX]; ) { *cp++ = 0 } Note: in this case, the pointer is compared with the internal training after the last element of the array, so the operation is OK
  • Case 2 #define datamax five
    int values[DATAMAX]
    int *cp
    //This test cannot be run on some compilers
    for(cp = &values[DATAMAX-1]; cp >= &values[0]; cp–)
    {
    *cp = 0
    }
    Note: this case compares the pointer with the memory before the first element of the array. It is OK in most C compilers, and some compilers cannot run normally. Responsible for
    Programmers who migrate code are a nightmare