Programming and Graphics

(Kiana) #1

5.2 Pointers to vectors and strings 135


Note that it isnotpermissible to state:


double * memad1 = &A;

A vector name is a pointer


The perfectly valid statement:

double * memad1 = A;

reveals that avector name is a pointer.The statement:


cout << *A << endl;

will print the first element of the vector (in our case 1.1), and the statement


cout << *(A+1) << endl;

will print the second element of the vector (in our case 1.2). Thus, the expression
A[0]is identical toA, the expressionA[1]is identical to(A+1), and the
expression


A[n]

is identical to


*(A+n)

wherenis an integer. In fact, the compiler blindly substitutes*(A+n), for every
instance ofA[n].


Vector layout


The following code contained in the filepointervector1.ccfurther illus-
trates the layout of a vector in a contiguous memory block:


#include <iostream>

using namespace std;

int main()
{
double A[3]={1.1, 1.2, 1.3};
double * memad1 = A;
double * memad2 = memad1+1;
double * memad3 = memad2+1;
Free download pdf