Array memory & array name +1

Source: Internet
Author: User

Last night, a small partner asked a question, feeling very classic.

  

1 inta[5] = {1,2,3,4,5};2 3 int*ptr = (int*) (&a +1);4 5printf"%d%d \n\r", * (A +1), * (PTR-1) );

From the memory distribution angle to resolve:

&a and a Do the right value when the difference:

&a is the first address of the entire array, and a is the first address of the first element of the array . The two are equal in numbers, but have different meanings. Different meanings can cause them to behave differently when they are involved in the operation.


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

&a is an array pointer whose type is int (*) [5]; so &a+1 is int (*) [5] + 1 as shown ,

&a+1 is equivalent to the entire array pointer plus 1, after executing &a+1, the PTR offset is equivalent to a + sizeof (int) * 5 * 1.

&a+2 is equivalent to the entire array pointer plus 2, after executing &a+2, the PTR offset is equivalent to a + sizeof (int) * 5 * 2.

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

Why do you need to force type conversions here, because the type does not match Ah, &a is an int (*) [5];ptr is an int * type. It is because of this coercion type conversion, so printf ("%d%d \n\r", * (A + 1), * (ptr-1));

Here ptr-1 is the last element of a sizeof (int) or a[5]. Some people can't figure out why-1 why not reduce to &a, is because here coercion type conversion . The main combination of two diagrams to understand, easy to understand.

Array memory & array name +1

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.