Home  >  Q&A  >  body text

c++ - 为什么指向数组的指针在自增时和普通指针自增时情况不同?

ringa_leeringa_lee2764 days ago566

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:33:06

    If the pointer p points to the i-th element of the array, then p+n, n+p, and p-n will point to the i+n, i+n, and i-n elements respectively.
    Here, the element pointed to by p is an array, so p+1 will point to the next array in the array. This is consistent with the behavior in other cases (such as when pointing to an int).

    Note: The cout line in your code contains undefined behavior. Refer to

    Has int array[10][20], (*p)[20] = array;

      The output of
    • std::cout << p++; is the same as std::cout << p;, which will output &array[0].

    • The output of
    • std::cout << ++p; is the same as std::cout << p+1;, which will output &array[1].

    • std::cout << p++; std::cout << ++p; will output &array[0] and &array[2].

    • std::cout << p++ << " " << ++p;Contains undefined behavior and the output of the program cannot be inferred.

    reply
    0
  • Cancelreply