18
POINTERS Pointer is a variable that holds the memory address of another variable of the same datatype. Pointer provides a way of manipulating variables directly through addresses without referring to the name of variable. Pointers supports Dynamic Memory Allocation. DECLARATION OF POINTER VARIABLES To declare a Pointer variable, the variable name must be preceded by an asterisk (*). The datatype (base type) of a Pointer should be the same as the datatype of the variable to which it will point( i.e. whose address it will store). Syntax to create a Pointer : datatype * varibale_name ; Examples: int * ptr1; //Pointer ptr1 can point to an int variable only. char * ptr2; //Pointer ptr2 can point to a char variable only. float * ptr3; //Pointer ptr3 can point to a float variable only. void * ptr; //Pointer ptr can point to any datatype variable.

Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

POINTERS Pointer is a variable that holds the memory address of another variable of the same datatype. Pointer provides a way of manipulating variables directly through addresses without referring to the

name of variable. Pointers supports Dynamic Memory Allocation.

DECLARATION OF POINTER VARIABLES To declare a Pointer variable, the variable name must be preceded by an asterisk (*). The datatype (base type) of a Pointer should be the same as the datatype of the variable to which it will point( i.e.

whose address it will store). Syntax to create a Pointer :

datatype * varibale_name ; Examples:

int * ptr1; //Pointer ptr1 can point to an int variable only.char * ptr2; //Pointer ptr2 can point to a char variable only.float * ptr3; //Pointer ptr3 can point to a float variable only.void * ptr; //Pointer ptr can point to any datatype variable.

Page 2: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

INITIALIZATION OF POINTER VARIABLEBefore using a Pointer variable it should be initialized with the address of another variable.

AddressOf Operator or Reference Operator (&) : When & is placed before a normal variable it returns the address of that variable. For example:

int A = 5;int *ptr1, *ptr2;ptr1 = &A ; //ptr1 stores the base address of variable A (i.e. the address of the 1st byte of variable.)ptr2 = ptr1 ; //now ptr2 also points to variable A

ValueAt Operator or Dereferencing Operator or Indirection Operator (*) : When * is placed before a Pointer variable it returns the value stored in the variable to which the Pointer variable is pointing to. For example:

cout<<*ptr1; // displays the value which is stored at the location where ptr1 is pointing to i.e. 5.cout<< ptr1; // will display a hexadecimal number representing an address i.e. 0x200

Page 3: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

Ques : Predict the output of the following :a. int r = 99, k = 78, *q;

r++;q = &k;k += r;cout<< *q << r << k << endl;

b. int r = 99, k = 78, *q, *w;w = &k;q = w;k++;cout<< k << *q << *w << (r+10) << endl;

c. int r = 99, *q;q = &r;(*q)++;cout<< *q << r++ << endl;

Ans:a. 178100178b. 797979109c. 101100

Page 4: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

POINTER ARITHMETIC A Pointer stores a hexadecimal number, which is the address of another variable. We can use ++, --, +, and - arithmetic

operators with Pointers. Only the following two arithmetic operations can be performed on Pointers : Addition of a number to a Pointer. Subtraction of a number from a Pointer.

Example 1. int * ptr, i = 25;ptr = &i;ptr++; // ptr now points to memory location of the adjacent variable of its data type.

Note: Each time an integer Pointer variable is incremented, it points to next integer and its value increases by 2 bytes. When a character Pointer is incremented, it points to next character variable and its value increases by 1 byte. When a float Pointer is incremented, it points to next float variable and its value increases by 4 bytes.

Example 2. ptr += 2; // it increments Pointer ptr by size of 2 integer variables i.e. 4 bytes.

We cannot perform the following arithmetic operations on Pointer variables : Addition of 2 Pointer variables can not be done. Multiplication/division of Pointer by a number can not be done.

Page 5: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

POINTER AND ARRAYSThe name of the Array is a constant Pointer which always holds the base address i.e. the address of the 0th element of the array

Example: int A[5]; // Here A represents &A[0]

Similarity between Pointers and Arrays1. Both the Array name and Pointer represents an address.2. You can use the bracket notation ([]) with Pointer also as with the Array name. For Example:

int A[] = {20,30,15} , *ptr;ptr = A; // Array name A is equivalent to &A[0], so ptr now points to 0th elementfor(int i=0; i<3; i++)cout<< ptr[i] <<endl; // ptr[i] refers to content at addresss equivalent to *(ptr + i);

3. You can apply the dereferencing operator i.e. ValueAt operator (*) with an Array name also as with a Pointer . For Example:int A[] = {20,30,25,22,27};for(int i = 0; i<5; i++)cout<< *( A+i ) << endl; // *(A + i) is equivalent to A[i];

Difference between Pointers and Arrays1. You can change the value of Pointer variable so that a Pointer can point to a new location but an Array name is a constant and its value

cannot be changed i.e. an Array name always points to 0th location of the Array and nothing else.int A[] = {20,30,35,22,27}, *ptr ;ptr= A; // Array name A is equivalent to &A[0], so ptr now points to 0th elementA++; // invalid will generate an error since Array name is a cost.ptr++; // ptr is incremented and now points to 1st element of Array

Page 6: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

Ques : Predict the output of the following :#include<iostream.h>void main(){int Array[] = {4,6,10,12};int * pointer = Array;for(int i = 1; i<=3; i ++){cout<<*pointer<<"#";pointer++;}cout<<endl;for(i = 1; i<=4; i++){(*pointer) *= 3;--pointer;}for(i = 1; i<5; i++){cout<<Array[i-1]<<"@";}cout<<endl;}

Ans : 4#6#10#12@18@30@36@

Page 7: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

POINTER AND STRINGSA string is a one dimensional array of characters terminated by a null character. In C++ a character array can be declared by two methods :

Method 1 : char S[] = “computer science”;Method 2 : char *S = “computer science”;

“Name of Character Array” , “Pointer to Character” and “Double quoted String Constant”, all of these are interpreted by C++compiler as the address of 0th character of string and are equivalent.

Normally if you give cout an int or float Pointer it will display a hexadecimal number representing an address stored in it, but if yougive cout a character pointer then it does not prints an address rather, it prints the character stored at that address and continuesprinting adjacent characters until the null character is encountered.

Example:#include<iostream.h>void main(){ char str1[] = “Works as an array”;

char *str2 = “Works as a pointer”;str1++; // Invalid name of array is a constant always pointing to 0th element.str2++; // valid str2 now points to 1st character and not 0th charactercout<<str1; // it will display - Works as an arraycout<<str2; // it will display - orks as a pointer

}Example 1 : 0th character of a string can be displayed by :

array notation as : cout << S[0]; pointer notation as : cout << *(S+0);

Example 2: 2nd character of string can be displayed by : array notation as : cout << S[2]; pointer notation as : cout << *(S+2);

Page 8: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

Ques : Predict the output of the following :#include<stdlib.h>#include<iostream.h>#include<string.h>#include<ctype.h>void changeString(char text[], int &counter){char *ptr = text;int length = strlen(text);for(; counter<length-2; counter+=2,ptr++)

*(ptr + counter) = toupper(*(ptr + counter));}void main(){int position = 0;char message[] = "PointersFun";changeString( message, position );cout<<message<<"@"<<position;}

Ans: PoiNteRsFUn@10

Page 9: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

PASSING AND RETURNING POINTERS FROM FUNCTIONS

In C++ a function can receive pointers as arguments and also return a pointer like any other datatype.datatype* name_of_function (datatype*, datatype*);

Ques . Write a Program which receives reference of two integer variables and then returns the reference of the largest.#include<iostream.h>int * large ( int*, int* );void main(){ int a, b, *c;

cout<<“enter two numbers”;cin>>a>>b;c = large(&a, &b); //addresses of a and b passed to functioncout<< “the largest number is” <<*c; // c is a pointer which contains an integer address

}int* large (int *m, int *n){ if(*m > *n)

return m;else

return n;}

Page 10: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

COMPARING DIFFERENT WAYS OF PASSING ARGUMENTS#include<iostream.h>void swapV( int , int );void swapR( int&, int& );void swapP( int*, int* );void main(){ int a, b, ptr;

do { cout<< “enter 2 numbers”;cin>>a>>b;cout<< “1 pass arguments by value”;cout<< “2 pass arguments by reference”;cout<< “3 pass arguments as pointers”;cout<< “exit”;cin>>ch;switch (ch){

case 1: swapV(a, b);cout<<a<<b; break;case2 : swapR(a, b);cout<<a<<b; break;case 3 : swapP(&a, &b);cout<<a<<b; break;

}} while(ch!=4);}

void swapV( int x , int y ) //call by value{ int z = x;

x = y;y = z;

}void swapR( int &x , int &y ) //call by reference x and y are alias names of a and{ int z = x;

x = y;y = z;

}void swapP( int *x , int *y ) { int z = *x;

*x = *y;*y = z;

} In function swapV( ) x and y are local variables created within the function and the

values of actual arguments is copied into them In function swapR( ) x and y are reference variables, they are only alias names of the

existing actual arguments In function swapP( ) x and y are created as pointer variables initialized with the

address of actual arguments i.e. they point to actual arguments

Page 11: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

ARRAY OF POINTERSPointers maybe arrayed like other datatype. Array of pointer contains collection of addresses.

The address present in the array of pointers can be address of isolated variables or addresses of array elements. For Exampleint * ptr[3] ; //array of integer pointersint n1 = 60, n2 = 50, n3 = 100; // isolated variablesptr[0] = &n1;ptr[1] = &n2;ptr[2] = &n3;for(int i = 0; i<3; i++)

cout<< *(ptr[i]); //6050100

An array of pointers can be used to store and manipulate many strings in memory. It is preferred over 2-D array of characters because - It makes efficient use of memory by consuming less number of bytes. It makes manipulation of strings easier. For example, one can change their order without actually touching them. Swapping elements

of ptr alters the order of pointed strings without the need of strcpy() as in 2-D array.char * ptr[3] = {“apple”, “mango”, “orange”}; //array of character pointerschar * temp = ptr[0];

ptr[0] = ptr[1];ptr[1] = temp;

for(int i = 0; i<3; i++)cout<< *(ptr[i]); //mangoappleorange

Page 12: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

PREFIX / POSTFIX OPERATIONS WITH POINTERS#include<iostream.h>void main(){int arr[]={30,40,50,60,70};int * ptr = arr;cout<< *ptr++; //30cout<< (*ptr)++; //40cout<< *ptr; //41cout<< ++(*ptr); //42cout<< *(++ptr); //50cout<< (*ptr)++; //50cout<< * ptr; //51cout<< ++ *ptr++; //52cout<< * ptr; //60}Output: 304041425050515260

In statement : cout<< ++ *ptr++; Both * and ++ operator have the same preference but they associate right to left. It means in *ptr++, the right ++ operators is associated with ptr and not with *ptrbut since ++ is a postfix form, the pointer will be incremented afterwards.

Page 13: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

POINTER AND CONST

A constant pointer means that the pointer always point to the same address and its address can not be modified. A pointer to a constant refers to a pointer which is pointing to a symbolic constant which cannot be modified.int m = 20; // integer m declarationint *p = &m; // pointer p to an integer m++ (*p); // increments the value stored at the variable where p is pointing to i.e. m becomes 21Constant Pointer to intint * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now++ c; // wrong : c is a const pointer its value (address) can’t be modified Constant Variableconst int cn = 10; // cn is a const integerPointer to a Constantconst int *pc = &cn; // pc is a pointer which is pointing to a const int++ (* pc); // wrong : value at the variable where pc is pointing is constant and can’t be modified++ pc; // increments pointer pc i.e. pc now points to the next integerConstant Pointer to a Constant intconst int* const cc = &cn; // cc is a const pointer to a const integer cn++ (* cc); // wrong : value at the variable where cc is pointing is constant and can’t be modified++ cc; // wrong: cc is a const pointer its value (address) can’t be modified }

Page 14: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

POINTERS TO STRUCTURESWhen a pointer holds the address of structure variable it is known as structure pointer. Syntax to declare is:

structure_name * pointer_name ;

Example:#include<iostream.h>struct stu{

int roll;char name[20];

};void main(){ stu S, *ptr ;

cin>>S.roll; gets(S.name);

ptr = &S;

cout<<ptr -> roll; // Arrow Operator(->) can be used to access the structure variable’s members through a Pointer

puts ( ptr -> name);

cout<<(*ptr).roll;puts ( (*ptr). name);

}

Page 15: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

C++ PROGRAMS MEMORY MAP

Free Store : Every C++ program is provided with pool of unallocated heap memory that it may utilize during runtime. This pool ofmemory is referred to as program free store. The allocated free store memory is unnamed. Variables allocated in the free storeare manipulated indirectly through pointers.

Static Memory Allocation: When amount of memory to be allocated is known beforehand and memory is allocated at time ofcompilation itself it is referred to as Static Memory Allocation.Example:

int a; //allocates 2 bytes of memoryint b[5]; //allocates 2x5=10 bytes of memory

Dynamic Memory Allocation: When amount of memory to be allocated is not know beforehand rather it is required to allocatememory as and when required during runtime itself then allocation of memory at runtime is referred to as Dynamic MemoryAllocation. The Operators new and delete are used to allocate and deallocate memory at run time.

STACK STACK memory is used for function calls, return addresses, arguments and local variables

HEAP HEAP memory is used for dynamic allocation of memory

Global Variables exist as long as the program continues

GLOBALVARIABLES

PROGRAM CODE

Page 16: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

NEW OPERATORThe new operator allocates the memory dynamically and returns the address of the allocated memory. The newly allocated memoryis in the free store and is unnamed i.e. no name for this memory location exists. Hence, it has to be referred only through the pointerpointing to it. The new operator can also be used to allocate memory for variables, arrays or structures.Eg. int * ptr1;

ptr1= new int; //memory equal to an int (2 bytes) is allocated in the free store and its address is stored in ptr1cin>>*ptr1;cout<<*ptr1;

Eg. char * ptr2;ptr2 = new char; //memory equal to a char ( 1 byte) is allocated in the free store and its address is stored in ptr2

Eg. int * ptra;ptra = new int[6]; //memory for array of 6 integers is allocated in the free store and its address is stored in ptra

Eg. struct address { int hno; char city[20]; };address * ptrs;ptrs = new address; //memory for a variable of struct address is allocated in free store and its address is stored in ptrscin>> ptrs -> hno;gets(ptrs-> city);

The newly allocated memory can be initialized at the time of its creation as follows :-pointerVariable = new Datatype (initialValue);

Eg. char * ptr1 = new char (‘a’);int * ptr2 = new int(5);float * ptr3 = new float(16.5);

Page 17: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

DELETE OPERATORThe memory allocated by new operator is not deleted even after execution of program. Thus when the memory allocated by new is no longer needed it must be destroyed or deallocated using delete operator so that it maybe released for reuse.Syntax : delete pointerVariable;Eg. delete ptr ; // deallocate the memory to which ptr is pointing to.

To deallocate memory allocated to arraysSyntax : delete [size] pointerVariable;Eg. delete [5] ptr;

ordelete[] ptr; //size can be skipped

MEMORY LEAKA memory leak occurs when a piece of memory that was previously allocated by a programmer is not properly deallocated by the programmer.

Page 18: Functions in mysql · int * const c = &m; // c is a const pointer to an integer ++ (* c); // increments value stored at variable where p is pointing to i.e. m becomes 22 now ++ c;

Ques. Write a program which would dynamically allocate memory for an array, Input the elements of array and find out or display the smallest element and its position.

#include<iostream.h>void main(){ int i, min, pos, size;

cout<< “Enter the size of array”;cin>>size;int * arr = new int[size];if (arr == NULL) //NULL is a constant which indicates that pointer is not pointing to any valid address

cout<< “array cannot be created, free store is full”;else { for(i = 0; i<size; i++)

{ cin>> *(arr + i);}

min = *(arr + 0);for( i = 1; i<size; i++){ if(*(arr + i) < min )

{ min = *(arr + i);pos = i;

}}

cout<< “\n smallest element is” <<min;cout<< “\n position is” <<(pos + 1);delete[] arr;

}