Você está na página 1de 25

POINTERS

Need for pointers: Pointers enable us to access a variable that is defined outside the function. Pointers reduce the length and complexity of a program. They increase the execution speed The use of pointer array to character strings results in saving of data storage space in memory.

The address of operator (&) Address occupied by a variable is returned using the address of operator &. Example: #include<iostream.h> void main( ) { int var1= 11; int var2 = 22; cout<< endl<< &var1; variables cout<< endl<<&var2; }

//print out the addresses of these

This simple program defines two integer variables and initializes them to the values 11 , 22. it then prints out the addresses of these variables. Here the output may be: 0x84ffff4, 0x84ffff2

Pointer Variables

A variable that holds an address value is called a pointer variable or simple pointer. Pointer variables declaration: data type *ptrvar; Data type of pointer variable must same as the type of variables address it will hold.

Example:
#include<iostream.h> void main( ) { int var1 = 11; int var2 = 22; int *ptr; ptr=&var1 cout<< endl<< &var1; cout<< endl<<ptr; ptr=&var2; cout<<endl<<&var2; cout<<endl<<ptr; }

//print out the addresses of these variables // display the address of var1 // display the address of var2 // display the address of var2

Accessing The Variable Pointed To :

Suppose that we dont know the name of a variable but we do know its address. Can we access the contents of the variable?
There is a special syntax to access the value of a variable using its address instead of its name. Asterisk (*) indirection addressing operator or value at address operator is used to return the value of the variable pointed to by pointer variable.

Example: #include<iostream.h> void main( ) { int var1 = 11; int var2 = 22; int *ptr; ptr=&var1 int x; x=*ptr; cout<< endl<< var1<<x<<*ptr; ptr=&var2; int y= *ptr; cout<<endl<<var2<<y<<*ptr; }

//print out the variables value as 11 // display the value of var2 as 22

Run: 11 11 11 22 22 22 Using the indirection operator to access the value stored in an address is called indirect addressing. int v; int *p; p=&v; v=3; *p=3;

// defines p as a pointer to int // assign address of variable v to pointer p // assign 3 to v //also assign 3 to v

The last two statements show the difference between normal or direct addressing, where we refer to a variable by name and pointer and indirect addressing, where we refer to the same variable using its address.

Pointer to void: Normally, the address that put in a pointer must be the same type as the pointer. We cant assign the address of a float variable to a pointer to int , for example. However, there is an exception to this. There is a general purpose pointer that can point to any data type. This is called a pointer to void. It is defined as follows: void * ptr;

A pointer can point to any data type variables address if it is declared as void type.

Example: #include<iostream.h> void main( ) { int x; float y; int *iptr; float *fptr; void *vptr iptr=&x; fptr=&y; iptr=&y; fptr=&x; vptr=&x; vptr=&y; }

//correct int * to int * //correct float * to float * //incorrect int * to float * //incorrect float * to int * //correct int * to void * //correct float * to void *

Pointers And Arrays: There is a close association between pointers and arrays Example:

#include<iostream.h> void main( ) { int arr[5]={43,56,67,23,69}; for(int j=0;j<5;j++) { cout<<arr[j]<<endl; } }


The cout statement prints each array elements in turn. Here the output is : 43 56 67 23 69

Array can be accessed using pointer notation as well as array notation. Example: using pointer notation #include<iostream.h> void main( ) { int arr[5]={43,56,67,23,69}; for(int j=0;j<5;j++) { cout<< *( arr+j ) <<endl; } }

The expression *( arr+j ) has the exactly same effect as arr[j].


Array variable returns the first location address. Here arr is the array name it gives the base address.

Another way of representing arrays using pointers

#include<iostream.h> void main( ) { int arr[5]={43,56,67,23,69}; int *ptr; ptr=arr; //ptr points to first location of array for(int j=0;j<5;j++) { cout<< * ptr <<endl; ptr++; } } Here ptr starts with the same address value as arr, thus allowing first array element, arr[0], which has the value 43, to be accessed. Because ptr is a variable it can be incremented. After it is increment ptr points to second array element arr[1].

Pointer to Object: Pointer can point to an object created by a class. Example: class test { int m1,m2; public: void get() { cout<<enter m1 m2 values; cin>>m1>>m2; } void display( ) { cout<<value of m1 and m2; cout<<m1<<m2; } };

void main( ) { test t1; cout<< Reading t1 object inputs; t1. get( ); // accessing members using direct addressing t1. display ( ); test *testptr; testptr = & t1; // t1 object address is given to ptr variable *(testptr). display ( ); // accessing members using indirect addressing } testptr -> display( ); // accessing members using indirect addressing

Run: Reading t1 object inputs enter m1 m2 values 34 56 value of m1 and m2 34 56 value of m1 and m2 34 56 value of m1 and m2 34 56

Pointer to Pointer:

C++ allows programmers to define a pointer to pointers, which offers flexibility in handling arrays, passing pointer variable to arrays.
Syntax for defining pointer to pointer is: data type **ptrvar;

Which uses two * symbols. It implies that prtvar is a pointer to a pointer addressing a data object of type data type.

Example: #include<iostream.h> void main( ) { int *iptr; int **ptrtoptr; int data; iptr=&data; ptrtoptr=&iptr; *ptr=100; cout<< the variable data contains<<data <, endl; **ptrtoptr= 200; cout<< the variable data contains<<data <, endl; data =300; cout<<Ptrtoptr is pointing to << **ptrtoptr <<endl; }

Run: the variable data contains : 100 the variable data contains : 200 Ptrtoptr is pointing to : 300 In main( ), the statement int **ptrtoptr; Creates a pointer variable which holds a pointer to another pointer variable. The statement ptrtoptr=&iptr; Assigns address of the pointer variable iptr to ptrtoptr. The value pointed by iptr can also accessed by ptrtoptr as follows **ptrtoptr The expression **ptrtoptr effectively accesses the contents of the variable data.

STRINGS
String is a group of characters A group of character can be stored in a character array.

A string is an array of characters or character array.


Strings are used in Programming languages for storing and manipulating text, such as words, names, sentences.

End of the string is marked by the NULL (\0) character.


String constants are enclosed in double quotes Example: Hello world A string is stored in memory by using ASCII codes of the characters that form the string. String Representation in Memory

String Declaration: An array of characters representing a string is defined as follows: char array_name[size]; size of the array must be an integer value. Eg. Char name[50]; Defines an array & reserves 50 bytes of memory for string a set of characters. The length of the string cannot exceeds49 since; one storage location must be reserved for string the end of the string marker.

Initialization at compile time:


Char array_name = {list of characters separated by comma};

For example: Char month = {A,P,R,I,L,\0}; Or Char month = April;

It has the same effect as the above statements. The compiler takes care of storing the ASCII codes of the characters of the string in memory, and also stores the NULL character at the end.

Example: Read & Display a string #include<iostream.h> void main() { char name[50]; cout<<ENTER YOUR NAME<49-max>; cin>>name; cout<<YOUR NAME IS<<name; } Run: Enter your name : Archanna Your name is Archanna

String Manipulation
C++ has several built-in fuctions such as strlen(), strcat(), strcmp(), strcpy()..etc, for string manipulation. To use these functions, the header file string.h must be included in the program using the statement. #include<string.h> i. String Length The string function strlen() returns the length of a given string. The length of the string excludes the end of string character(\0). Syntax: int var=strlen(string variable);

Example: #include<iostream.h> #include<string.h>

void main() { char s1[20]; cout<<Enter Your name; cin>>s1; cout<<Strlen(s1)<<strlen(s1); }

Run: Enter Your name: Smrithi Strlen(s1):7

ii. String Copy The string function strcpy() copies the contents one string to another. Syntax: strcpy(string, string2);

String1-> destination string String2-> source string Source string is copied into destination string.

Example:

#include<iostream.h> #include<string.h> void main() { char s1[20],s2[20]; cout<<Enter Your name; cin>>s1; strcpy(s2,s1); cout<<Strcpy(s2,s1): content of s2 is:<< s2; } Run: Enter Your name: Smrithi Strcpy(s2,s1): content of s2 is: Smrithi

iii. String concatenation:

The string function strcat() concatenates two string resulting in a single string.
Syntax: strcat(string1, string2);

String1-> destination string String2-> source string The destination & Source strings are concatenated and the resultant string is stored in the destination string. Example:

#include<iostream.h> #include<string.h> void main() { char s1[20],s2[20]; cout<<Enter Your first name; cin>>s1; cout<<Enter Your second name; cin>>s2; strcat(s2,s1); cout<<Strcat(s2,s1): content of s2 is:<< s2; } Run: Enter Your First name: Roy Enter Your Second name: Joy Strcat(s2,s1): content of s2 is: RoyJoy

iv. String Compare: The string function strcmp() compares two strings, character by character. It returns an integer, whose value is
< 0 if first string is alphabetically higher than second string. = = 0 If both are identical > 0 if first string is alphabetically lower than second string.

Syntax: strcmp(string1,string2); ASCII codes of each character in the given strings are compared. Once it find mismatch ASCII code it stop comparing and returns the difference between the ASCII value of mismatched string is returned. Example:

#include<iostream.h> #include<string.h> void main() { char s1[20],s2[20]; cout<<Enter name1; cin>>s1; cout<<Enter name2; cin>>s2;

int i=strcmp(s2,s1); if( i= = 0 ) cout<<Name1 and name2 are same; else if(i<0) cout<< Name1 is alphabetically higher than name2 ; else cout<< Name1 is alphabetically lower than name2 ;

Run1: Enter name1: Roy Enter name2: Joy Name1 is alphabetically lower than name2 Run2: Enter name1: Roy Enter name2: Roy Name1 and name2 are same Run3: Enter name1: Roy Enter name2: roy Name1 is alphabetically higher than name2 Note: Remaining manipulators refer Book

ARRAYS OF STRINGS An array of strings is a two dimensional array of characters and is define as follows: Syntax: char arry_name[row size][col size]; row size-> No of strings can be stored col size-> no of characters in each string. Example: char person[10][15];

It defines an array of strings which can store name of 10 persons and each name cannot exceeds 14 characters. Last one character is used to represents the end of a string. Example: Array of strings storing names

#include<iostream.h> #include<string.h> void main() { char person[10][15]; cout<<How many persons <max-10>; cin>>n; for(int i=0;i<n;i++) { cout<<enter person<<i+1<<endl; cin>>person[i]; }

cout<<Person names; for( i=0;i<n;i++) { cout<<person[i]<<endl; }

Run: Enter Persons <max-100> 2 Enter person1: Roy Enter person2: Joy Person names Roy Joy Problem: Write a C++ program to perform sorting of N names in descending order.

Você também pode gostar