Confusions about (& A + 1)

Source: Internet
Author: User

Take a look at the following programs:

Q:

If int A [5];

What does & A + 1 mean?

A:

& A + 1 does not indicate that the address of a (set to ox0010) is added with 1 and becomes 0x0011. because a is an array of five int types, "+ 1" in "& A + 1" indicates a space equivalent to "1" A size (or an offset ), in this case, & A + 1 indicates a [5].

Q:

If int * PTR = (int *) (& A + 1 );

What does PTR mean?

What does PTR-1 mean?

A:

Since & A + 1 indicates a [5], PTR is a [5].

PTR is int type pointer, so "ptr-1" will subtract "1" int type pointer space, this is a [5-1] = A [4].

Take a look at the specific procedures below:

Main ()

{

Int A [5] = {1, 2, 3, 4, 5 };

Int * PTR = (int *) (& A + 1 );


Printf ("% d, % d", * (a + 1), * (ptr-1 ));

}

Output: 2, 5

Explanation:

* (A + 1) is a [1], * (ptr-1) is a [4], the execution result is 2, 5

& A + 1 is not the first address + 1. The system will consider that the offset of adding an array a is the offset of an array (in this example, It is 5 Int values)

Int * PTR = (int *) (& A + 1 );

Then PTR is actually & (A [5]), that is, a + 5

The reason is as follows:

& A is an array pointer and its type is int (*) [5];

The pointer plus 1 must add a certain value based on the pointer type,

Different types of pointers + 1 increase with different sizes

A is an int array pointer with a length of 5, so you need to add 5 * sizeof (INT)

Therefore, PTR is actually a [5].

But the PRT and (& A + 1) types are different (this is important)

So the prt-1 will only subtract sizeof (int *)

A, & A has the same address but different meanings. A is the first address of the array, that is, the address of a [0], and a is the first address of the object (array, A + 1 is the address of the next element of the array, that is, a [1]. & A + 1 is the address of the next object, that is, a [5].

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.