NIOS Computer Science: Chapter 15 – Pointer Part 2

Download PDF of This Page (Size: 222K)

Image of Pointer to Array

Image of Pointer to Array

Image of Pointer to Array

1. Pointer to Array

Consider the following declaration:

int A [ 5 ];

The name of the array A itself is a pointer which holds the address of zero location (&A[0]).

It is a constant in a program, its value cannot be changed. The following program prints all the values of an array A.

# include < iostream.h >

void main ( )

{

int [5] = { 20, 35, 25, 22, 27 };

for (int i = 0; i < 5; i + + )

cout << “\n” << A [ i ];

}

The output is :

20

35

25

22

27

The above program can be written as pointer notation.

# include < iostream.h >

void main ( )

{

int A [5] = { 20, 35, 25, 22, 27 }

for (int i = 0; i < 5; i + + )

cout << “\n” << *(A + i);

}

At one stage the value of i is 2. Therefore is 2, i.e., two locations from the zero

location. The will print the data stored at that location.

2. Pointer to String Constant

Consider the following example:

# include < iostream.h >

void main ( )

{

char stu1 [ ] = “work as an array”;

char *stu2 = “work as a pointer”;

cout << stu 1;

cout << stu2; // display both the strings

stu1 ++; / / it is a wrong statement

stu2 + +;

cout << stu2; / / it prints “ork as a pointer”

}stu 1 + + is a wrong statement because stu 1 is a pointer which holds the address of zero location ( & stu1 [0]). It is a constant in a program.

3. Pointer to Structure

Consider the following program

struct student

{

char name [30];

int rn;

};

The statement

student st;

declares st as the variable of the structure student.

The statement

student *ptr;

declares a pointer variable ptr to a student.

That data members using ptr can be referred to as

ptr -> name;

ptr -> rn;

Another way of referring the data member is

(*ptr).name;

(*ptr).rn;