C language address for array name

Source: Internet
Author: User

Author: Qing Dujun


Have you ever thought about getting an address for a one-dimensional array name and then using this address for addition and subtraction. What will happen?

Example:

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

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

Printf ("% d \ n", * (p-1 ));


What is the output?

Why? Why do we need to forcibly convert the type in the second line?

A: a is the name of a one-dimensional array, and a corresponds to a pointer pointing to a one-dimensional array. How do you feel so familiar? Is that a row pointer to an array? Int (* p) [].

The row pointer + 1 is used to add or subtract the pointer. The result is still a row pointer ~~~ Originally, it was required to be forcibly converted to a single pointer.


So what is the output result?

A: Of course, it is 5.

Why?

A: I didn't mean that & a is a row pointer, that is, a row pointer. The row pointer + 1 does not point to the next row. Here the row is [5], so int * p = (int *) (& a + 1) it is necessary to deviate from five positions on the basis of a: (the last line indicates the number of digits, and the next line indicates the corresponding data in)

0 1 2 3 4 5

1 2 3 4 5 *

Isn't that out of bounds? Moving the five digits all ran out of the [] array in the '*' position. Oh, I see the output of printf. What you output is P-1). Here, p is a single pointer-1, which is just a shift to the left. Isn't it the return to the position 5? It turns out that the output result is 5.


Next we will use a piece of code to show the displacement ~~~

# Include
 
  
Int main () {int a [5] = {1, 2, 3, 4, 5}; int * p = (int *) (& a + 1 ); // + 1 is equivalent to moving five digits of printf ("% p \ n % p \ nbit = % d \ n", a, p, p-); printf ("% d \ n", * (p-1); return 0 ;}
 


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.