Interview series 10 - understanding of the addition and subtraction of the pointer

xiaoxiao2021-04-05  277

Original title: main () {int A [5] = {1, 2, 3, 4, 5}; int * ptr = (int *) (& A 1); Printf ("% D,% D", * (A 1), * (PTR-1));} What is the program output?

Answer: Program output: 2,5

Analysis: Here is mainly to investigate the understanding of the decrease in the pointer. Add 1 operation to the pointer, resulting in the address of the next element, rather than the original address value plus 1. Therefore, the movement of a pointer type T is the mobile unit with SIZEOF (T).

Therefore, for the topic, A is a one-dimensional array, 5 elements in the array; PTR is an INT type pointer. & a 1: Take the address of A, the value of this address plus the value of SizeOf (a), that is, the address of the A [5], obviously the current pointer has crossed the boundaries of the array . (INT *) (& A 1): The address calculated by the previous step, forced to convert to an int * type, assign the value to the PTR.

* (A 1): a, the address of & a is the same, but the meaning is not the first address, that is, the address of the A [0], & A is the first address of the object (array), A 1 is an array The address of the next element, that is, A [1], & A 1 is the address of the next object, namely A [5]. So output 2

Modify: * (A 1): Output 2. Analysis: a, & a address is the same, but the meaning is not the same, A is the first address of the group, that is, the address of the A [0], & A is the first address of the object (array), A 1 is the address of the next element of the array , Ie A [1], & A 1 is the address of the next object, ie A [5].

* (PTR-1): Because the PTR is pointing a [5], and the PTR is an int * type, * (PTR-1) is pointing to a [4], output 5.

转载请注明原文地址:https://www.9cbs.com/read-132164.html

New Post(0)