• No results found

Array of pointers:

N/A
N/A
Protected

Academic year: 2021

Share "Array of pointers:"

Copied!
14
0
0

Loading.... (view fulltext now)

Full text

(1)

Array of pointers:

As we have array of integers , the same way we have array of pointers. Array of pointers can store the addresses of variables.

The each element or index of array can store the memory address.

The array of pointer can store the memory addresses of different objects of same type.

Program:

#include<iostream.h>

// topic : array of pointers main()

{

int *ptr[3];

int a=10;

int b=20;

int c=30;

ptr[0]=&a; // assinging address of variable 'a' to zero index of pointer array ptr[1]=&b; // assinging address of variable 'b' to one index of pointer array ptr[2]=&c; // assinging address of variable 'c' to two index of pointer array

for(int i=0;i<3;i++) {

cout<<*ptr[i]<<endl; // output: 10,20,30 }

}//end of main

(2)

Pointers and Function

C++ allows you to pass a pointer to a function as parameter.

To do so, simply declare the function parameter as a pointer type.

Following a simple example where we pass two integer type of pointers to a function and change the value inside the function which reflects back in the calling function:

void show_ab_byvalue(int,int);

void show_ab_bypointer(int*,int*);

void main() {

int a,b;

cout<<"Enter first integer:";

cin>>a; //3

cout<<"Enter second integer:";

cin>>b; //4

show_ab_byvalue(a,b);

cout<<"value of first integer after calling funciton:"<<a<<endl; //3 cout<<"value of second integer after calling funciton:"<<b<<endl; //4

show_ab_bypointer(&a,&b);

cout<<"value of first integer after calling funciton:"<<a<<endl; //100 cout<<"value of second integer after calling funciton:"<<b<<endl; //4 }//end of main

(3)

void show_ab_byvalue(int x,int y) {

cout<<"inside x is:"<<x<<endl;

cout<<"inside y is:"<<y<<endl;

x=100; // calling function changed the value of parameter }

void show_ab_bypointer(int *x,int *y) {

cout<<"inside x is:"<<*x<<endl;

cout<<"inside y is:"<<*y<<endl;

*x=100; // calling function changed the value of parameter }

What is difference between parameter passing by reference and by pass by pointer.

The main difference is that the parameters in function definition in pass by reference is an alias of the parameters used in function call.

While parameters in function definition in pass by pointer is actually the address of the parameters used in function call.

In short the calling function pass the address of its parameters to the parameters of function definition.

(4)

Pointers to Structures (Pointers and structure):

Structures can be pointed by its own type of pointers.

However the dot (.) operator is not used to access the members of a structure when pointers are used to refer to a structure variable.

The selection operator or arrow operator is used ( -> ) instead of dot operator to access the structure member. It consists of minus sign and greater than sign.

Write a program that declares a structure to store the record of a book. It defines a structure variable, inputs the values and displays them using the pointer.

#include<iostream.h>

struct Book {

char name[30];

int pages;

int price;

};//end of structure

void main() {

Book rec;

Book *bptr;

bptr=&rec;

cout<<"Enter Book Details"<<endl;

(5)

cout<<"Enter Book Name:";

cin>>bptr->name;

cout<<"Enter Book Pages:";

cin>>bptr->pages;

cout<<"Enter Book Price:";

cin>>bptr->price;

cout<<"Display Book Details"<<endl;

cout<<"Author of Book:"<<bptr->name<<endl;

cout<<"Pages of Book:"<<bptr->pages<<endl;

cout<<"Price of Book:"<<bptr->price<<endl;

}//end of main

(6)

Memory Management with Pointers:

1-Memory management:

The process of allocating and deallocating memory is known as memory management.

The different operating systems sets up different areas of memory according to the requirement when a program starts execution.

Some important areas in the memory are as follows:

1.1-Global Name Space:

This memory is used to store the global varaibles.

1.2-Registers:

These are special memory units built into CPU.

1.3-Code Space:

It contains the program code (instructions or statements given in program) 1.4-Stack:

This memory contains the local variable and function parameters. It is also called static memory.

This memory is called static because the during compilation process the memory is allocated to local variables and function parameters.

1.5- Free Store:

It is the remaining memory. It is also known as heap or dynamic memory.

It is used during the execution of program.

2. Dynamic variables:

A variable that is created during the execution of program or at run time is called the dynamic variable. A dynamic variable occupies the memory from heap or dynamic memory.

The dynamic variable is created in C++ using the pointers.

(7)

The C++ provides two operators

new

and

delete

operators for dynamic variables.

new and delete are keywords in C++.

The new operator is used to create dynamic variables and delete operator is used to delete the dynamic variables during program execution.

Use of new Operator:

The new operator is used to allocate memory dynamically. It is followed by the type of object or variable for which the memory is to be allocated dynamically.

The compiler allocates the amount of memory according to type of object.

The new operator returns a memory address. The returned address must be assigned to a pointer.

The pointer is then used to access the memory location and process the values stored in that address.

The new operator can be used to create simple variable, an object or an array of objects.

Syntax:

The following syntax is used to create one variable dynamically new DataType;

The following syntax is used to create an array dynamically.

new DataType[length];

Example:

int *ptr; //declares an integer pointer variable

ptr=new int; //new operator used to create an integer variable in memory dynamically.

The address of the allocated memory is stored in the pointer ptr.

*ptr---int

The above figure shows that newly created memory has no name. it can only be accessed using the pointer.

(8)

Example:

Int *ptr; // declares and integer pointer variable

ptr=new int[5]; // new operator used to create an array of integers in the memory dynamically.

In above statement the address of first element of the array is stored in the pointer ptr.

*ptr---int[length]

Uses of delete operator:

The delete operator deallocates the memory and return the allocated memory back to the free store.

It takes a pointer as parameter and releases the memory referred by the pointer. The dynamically created object or data type should be deleted when it is no more required.

The pointer declared in the body of user define function is treated as local variable. The pointer goes out of the scope and is lost when the control exists from the function in which the pointer is declared.

However, the memory allocated with new operator is not freed automatically so that memory becomes unavailable. This situation is called the memory leak. This memory cant be recovered until the program ends.

Syntax:

The following syntax is used to delete one variable dynamically:

delete variable;

the following syntax is used to delete an array dynamically:

delete[] variable;

Example:

delete ptr;

the above statement will deallocate the memory reffered by the pointer ptr. The use of delete operator is slightly different when it refers to an array. The following statement is used if the pointer ptr referes to an array:

(9)

delete[] ptr;

Program:

Write a program that uses new operator to create an integer, input value in it and then displays that value.

#include<iostream.h>

main() {

int *ptr;

ptr=new int;

cout<<"Enter an integer:";

cin>>*ptr; // assigning value to the pointer cout<<"you entered:"<<*ptr<<endl;

cout<<"it is stored at"<<ptr<<endl;

delete ptr;

}//end of main

Program:

Write a program that inputs the length from the user and declares an array of integers of length specified by the user. The program then inputs the values in array and displays them.

(10)

#include<iostream.h>

void get(int*,int);

main() { int n;

int *ptr;

cout<<"Enter the length of array:";

cin>>n;

ptr=new int[n];

get(ptr,n); //calling function

cout<<"you entered following values"<<endl;

for(int j=0;j<n;j++) {

cout<<*ptr++<<endl;

}

delete[] ptr;

}//end of main

(11)

void get(int *p,int len) {

for(int i=0;i<len;i++) {

cout<<"Enter an integer:";

cin>>*p++;

}

}//end of get()

The above program declares a pointer variable ptr. it inputs the length of array and create an array of integers dynamically according to given length. The program passes the address of array and its length to the function get(). The loop in the function inputs values in the array.

The loop is executed according to the length of the array.

Finally, the program displays the values in the array and deletes the array using delete operator.

(12)

Dangling pointer:

Dangling pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

Dangling pointers arise when an object is deleted or deallocated, without

modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.

{

char *dp = NULL;

/* ... */

{

char c;

dp = &c;

}

/* c falls out of scope */

/* dp is now a dangling pointer */

}

(13)
(14)

References

Related documents

The respirable fraction is defined as the fraction of the released material associated with an Activity Median Aerodynamic Diameter (AMAD), of 1 mm (see Appendix B).. The

In this paper, we’ll look at the first steps in measuring your AppSec program, starting with how to use metrics to understand what is working and where you need to improve,

The project “System Actions to Support Social Integration and Employment Policies on Behalf of Migrant Workers” was a first effort to manage the recruitment of a foreign workforce

One type conceives of dispersion of authority to multi-task, territorially mutually exclusive jurisdictions in a relatively stable system with limited jurisdictional levels and a

Affiliates have to directions saint paul international airport authority and mall of the reservation only organization from the ground level up and by the.. dutch john fly

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

We discussed many examples of this interaction, for different types of institutions (such as political and legal institutions, regulation, and the welfare state) and