Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - The difference between address a and a+ 1 in the array int a[n] is 4, but why is a+ 1-a not 4 but 1?
The difference between address a and a+ 1 in the array int a[n] is 4, but why is a+ 1-a not 4 but 1?
int? a[n]; The above line of code declares an integer array named a, in fact, a here is an address, which is the address of the 0 th (first) element of the array.

int? b? =? a[2]; ? //Used here? 2? For example, to avoid 0? And then what? 1? The particularity is easy to understand. The process of "making b equal to a[d]" in this line is actually to perform an operation named "[]" on addresses A and 2 and return the contents of the new address. The process is like this:

The content pointed by address A is an integer (as can be seen from the declaration), so sizeof(int) gets 4, which means that an int value accounts for 4 bytes.

The "[]" operation is actually adding the address a and the 4× subscript. What you get here is the address position of "a+8 (bytes)".

Returns the contents of "a+8 (bytes)" and assigns it to the b variable.

The above "a+8 (byte)" is the operation of the address, but it cannot be written like this in the expression. In an expression, the operation of an address and an integer will convert the integer and the type pointed by the address into the same unit. For example:

int? A []? =? { 1,? 2,? 3};

int*? address 1? =? & amp(a[0]);

int*? Address 2? =? & amp(a[ 1]);

int? ans? =? Address 2? -? address 1; ? //? ans? =? 4? /? sizeof(int); ? ans? Equal to? 1

int? ans2? =? int(address2? -? address 1); ? //Explicitly converted to an integer. Ans and ans2 are in units of "sizeof (type) bytes". Here are 4 bytes, and the result is exactly the same, except that ans is written by implicit type conversion. The difference obtained by the address difference is divided by the size of this type and becomes an integer.

You can also try the bool type. Bool type takes up one byte.

Bull? b[]? =? {0,? 1,? 1};

Bull? *? Address 3? =? & amp(b[0]);

Bull? *? Address 4? =? & amp(b[ 1]);

int? ans3? =? Address 4? -? Address? 3; Ans3 or 1. Because bool takes up one byte, the address is divided by 1 to get 1.

The expression "(address 3+ 1) == address 4" is true. Because 1 is converted into 1 * sizeof(bool) or 1.

Therefore, in practical application, the distance between two known addresses of the same type can be obtained by addition and subtraction. The distance unit here is the number of bytes occupied by this type.