C ++ address addition constant

Source: Internet
Author: User

Main (){

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

Int * ptr = (int *) (& a + 1 );

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

}

Output: 2, 5

* (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 an array a is the offset of an array (in this example, it is five int values) int * ptr = (int *) (& a + 1 ); the ptr is actually & (a [5]), that is, the reason for a + 5 is as follows: & a is an array pointer and its type is int (*) [5]; the pointer plus 1 should add a certain value according to the pointer type, and the size of the pointer plus 1 of different types will be different. A is an int array pointer with a length of 5, so you must add
5 * sizeof (int) So 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 address is the same, but the meaning is not the same, a is the first address of the array, that is, a [0] address, & a is the first address of the object (array), and 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.