This is a Clilstore unit. You can link all words to dictionaries.

Pointers and arrays. Use of pointers with arrays

The array name can be interpreted as a pointer-constant for the array. For example, array int A [10]is declared in the program. In this case, A is a pointer for zero element of the array in the computer memory. In this respect,A==&=A =[0] is true relation.

To access the array elements except indexed names, it is possible to use dereferencing pointers on the principle:

name [index]is identically * (name + index)

For example: A [10] is identically *(A + 10) is identically *(10 + A).

In C ++ language, character [ plays the role of the sign of operation of addition of the array address with the array element index.

Example 63. Consider the function of squaring elements of the one-dimensional array. A pointer to the array is used as the function parameter.

// function description

void SQR (int n, float *x)

{ int i;

for( i=0; i<n; i++)

// multiplication and assignment

*(x+i)*=*(x+i); }

main()

{

// array description

float z[]={1.0, 2.0, 3.0, 4.0};

int j;

SQR(4,z); //

// display of the obtained array

for (j=0; j<4; j++)

cout<<\n z[”<<j<<”]”<<z[j];

}

As a result of work of the program, the following values will be displayed:

z[0]=1.000000

z[3]=16.00000

In the program instead of the command with useof the pointer *(x+i)*=*(x+i), it is possible to use entry x[i]=x[i]*x[i] or x[i]*=x[i].

Example 64. The program determines Euclidean norms of the matrix rows. Euclidean norm of vector is called the square root of the sum of squares of its elements. If consider each matrix row as a vector, then the formula shall be applied to each row. Counting of Euclidean norm will be carried out using function Evk. The pointer to the array shall be used as second function parameter.

#include <iostream.h>

#include<math.h>

float Evk (int n, int *x)

{int i; float s=0,p;

for (i=0; i<n; i++)

s+=*(x+i)**(x+i); p=sqrt(s); return p;}

main()

{ int a[3][4]={1,2,3,5,

1,1,1,1,

4,1,2,1};

float k; int j;

for (j=0; j<3; j++)

{k=Evk(4,a[j]);

cout<<"\n k="<<k;}

}

As a result of work of the program, the following values will be displayed:

k=6.245

k=2

k=4.69042

Short url:   http://multidict.net/cs/6256