The relationship between array and pointer types in C + +

Source: Internet
Author: User

The contents of arrays and multidimensional arrays are no longer discussed here, as explained in the previous tutorial, where the relationship between the array and the pointer type is more deeply understood by the understanding of the relationship between the array and the pointer.

An array of integer types is defined as follows:

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

If you simply write:

Identifier name of the a;//array

This will represent the memory address of the first element of the array, A; it is equivalent to &a[0], its type is a pointer to an array element type, in this case its type is int*

If we want to access the address of the second element we can write the following two ways:

&a[1];

a+1//Note that the representation here is to move the starting address of a array to the last one, to the address of the second element, i.e. a[0] to a[1]!

The relationship between the array name and the pointer is actually very simple, in fact, the array name represents the array of the first element of the memory address, which is similar to the principle of the pointer!

Here we look at a complete example, using pointers to achieve circular traversal of the array elements of access!

#include <iostream>
using namespace Std;
void Main (void)
{
int a[2]={1,2};
int *pb=a; Defines the address of the pointer *PB the starting address for array a
int *pe=a+2; Defines the address of the pointer *PB the end address of array a
cout << a << "|" << a[0] << "|" << * (a+1) << "|" << PB << "|" << *PB <<endl;
while (PB!=PE)//using the address to logically determine whether the end address of the array is reached
{
cout << *PB << Endl;
pb++; Increments the PB's memory address backwards in the loop using the increment operation
}
Cin.get ();
}

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.