Relationship between C ++ arrays and pointer types

Source: Internet
Author: User
1.

The following array definitions are known.
Int Ia [] = {0, 1, 1, 2, 3, 5, 8, 13, 21 };
Therefore, it is easy to write.
IA;
What does it mean?
The array identifier represents the address of the first element in the array. Its type is the pointer of the array element type. In Ia, its type is int *. Therefore, the following two forms are equivalent. returns the address of the first element of the array.
IA;
& Ia [0];

Similarly, to access the corresponding value, we can take one of the following two methods:
// Both get the value of the first element
* IA;
IA [0];
We know how to use the subscript operator to access the address of the second element.
& Ia [1];


Similarly, the following expression
IA + 1;


The address of the second element can also be obtained. Similarly, the following two expressions can access the value of the second element.
* (IA + 1 );
IA [1];


But the following expression

* Ia + 1; // The unreferenced operator has a higher priority than the addition operator. The result is to add 1 to the first element.
It is completely different from the following expression.
* (IA + 1); // The bracket operator has a higher priority than the unreferenced operator. The result is the value of the second element.

 

2.

Traverse arrays through pointers

# Include <iostream>
 
Template <class elemtype> // Template Function
Void print (elemtype * pbegin, elemtype * pend)
{

// The pend pointer executes the next bit of the last element
While (pbegin! = Pend ){
Cout <* pbegin <'';
++ Pbegin;
}
}

// Main Function

Int main ()
{
Int Ia [9] = {0, 1, 1, 2, 3, 5, 8, 13, 21 };
Double da [4] = {3.14, 6.28, 12.56, 25.12 };
String SA [3] = {"Piglet", "Eeyore", "Pooh "};
Print (IA, Ia + 9); // The second parameter Pointer Points to the next position of the last element of the array
Print (Da, da + 4); // da + 3 + 1
Print (SA, Sa + 3); // SA + 2 + 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.