Programming Fundamental Instructor Name: Muhammad Safyan Lecture-Pointers Pointers

Programming Fundamental Instructor Name: Muhammad Safyan Lecture-Pointers Pointers

Programming Fundamental Instructor Name: Muhammad Safyan Lecture-Pointers Pointers Pointer is most powerful features of the C++ programming language. References can be used to perform pass-byreference Pointers also enable pass-by-reference and can be used to create and manipulate dynamic data structures (i.e., data structures that can grow and

shrink) such as linked lists, queues, stacks and trees. Pointers Pointer variables contain memory addresses as their values. Normally, a variable directly contains a specific value pointer contains the memory address of a variable that, in turn, contains a specific value. A variable name directly references a value and a pointer indirectly references a value Referencing a value through a pointer is often called indirection

Pointers Pointers, like any other variables, must be declared before they can be used Pointers Declaration int *countPtr, count; "countPtr is a pointer to int "countPtr points to an object of type int. double *xPtr, *yPtr; Pointers should be initialized either when they

are declared or in an assignment A pointer may be initialized to 0, NULL or an Address. Assigning Null Value to Pointer A pointer with the value 0 or NULL points to nothing and is known as a null pointer. Symbolic constant NULL is defined in header file

(and in several other standard library header files) to represent the value 0 Pointer with Address Operators The address operator (&) is a unary operator that returns the memory address of its operand int y = 5; // declare variable y int *yPtr; // declare pointer variable yPtr yPtr = &y; // assign address of y to yPtr Getting Pointer value Use this operator (*) to get the value and can do any arithmetic operation with it.

ptr=&z; z = *ptr + 2 ; z = *ptr * 2 ; z = *ptr 2 ; Passing Arguments to Functions by Reference with Pointers There are three ways in C++ to pass arguments to a function Pass-by-value pass-by-reference with reference arguments pass-by-reference with pointer arguments

Reference arguments also enable programs to pass large data objects to a function and avoid the overhead of passing the objects by value (which, of course, requires making a copy of the object). Passing Arguments to Functions by Reference with Pointers Pointers, like references, also can be used to modify one or more variables in the caller or to pass pointers to large data objects to avoid the overhead of passing the objects by value. Pointer in Function

use pointers and the indirection operator (*) to accomplish pass-by-reference . When calling a function with an argument that should be modified, the address of the argument is passed. This is normally accomplished by applying the address operator (&) to the name of the variable whose value will be modified. void fn ( int *num) { statement(s) ; Pointer in Function

*num in the function declaration indicates that the receiving variable is pointer to a memory address. In the body of the function we will use this variable as: cin >> *num ; statement describes that the value entered through the keyboard (as cin is used) will be stored at the memory address wherever the Swapping two value(with Pointer) temp = x ; x=y;

y = temp ; ======================= yptr = &y ; xptr = &x ; swap (yptr, xptr) ; swap (int *yptr, int *xptr) { .. . } Using const with Pointers When we pass an array to a function, actually the

starting address of the array is passed to the function Thus the default calling mechanism to call a function while passing an array to it is a call by reference. At some

other occasion, we may pass the

addresses for efficiency while not affecting the values at that addresses. The use of const can be helpful in overcoming this problem. Using const with Pointers int *const myptr = &x ; Right hand side of this assignment statement could be read as, myptr is a constant pointer to an integer. Being a constant pointer, it should immediately point to something. Therefore, we assign this pointer an address of a variable x at the time of

declaration. Now this pointer cannot be changed.

use of keyword const in declaration statement Using const is Tricky const int *myptr = &x ; myptr is a pointer to a constant integer. This means that the value of pointer myptr can be changed but the cannot be changed value stored at that location

Relationship between Array and Pointer The name of the array is a constant pointer which contains the memory address of the first element of the array. The difference between this and an ordinary pointer is that the array name is

a constant pointer. name is a point to the start of array. int y[10]; int *yptr; yptr = y; Both pointing to the same place. It means array

Pointer Expressions and Arithmetic We can manipulate arrays with both y and yptr access the fourth element of the array using y, we can say y[3]. we can write as *(yptr + 4). Yptr=y It means that yptr contains the address of th e first element of the array. However, when we say yptr++, value of yptr is incremented. But how Pointer Expressions and Arithmetic

The data type, the pointer points to, determines the amount of increment. In this case, yptr is an integer pointer. when we increment the yptr,

it points to the next integer in memory Pointer with an array main() { Int y[10]; Int *yptr; Yptr=y; cout <

cout <

*(yptr + 5) << endl; cout < main () { int y[10] = {10,20,30,40,50,60,70,80,90,100}; int *yptr, i; yptr = y; // Assigning the address of first element of array. for (i = 0; i < 10 ; i ++)

{ cout<< \n The value of the element at position << i << is << *yptr; yptr ++ ; } } Example /* Program using pointer arithmetic */ include # main() { int x =10;

int *yptr; yptr = &x; cout << The address yptr points to = << yptr << endl ; cout << The contents yptr points to = << *yptr << endl; (*yptr) ++; cout << After increment, the contents are << *yptr << endl; cout << The value of x is = << x << endl; } Example (Arithmetic Operation) we can do different arithmetic operations with pointers. we have two pointers yptr1 and yptr2 to integer and

written as yptr1 + yptr2 ; The compiler will show an error in this statement main () { int y[10], *yptr1, *yptr2; yptr1 = &y[0]; yptr2 = &y[3]; Pointer Comparison Two pointers can be compared. Pointers can be used in conditional statements as

usual operators variables. can be All used

the comparison with pointers i.e. less than, greater than, equal to, etc Suppose in sorting an array we are using two pointers. To test which pointer is at higher address, we

can compare them and take decision depending on the result. Pointer Comparison main () { int x, y, *xptr, *yptr; cout << " \n Please enter the value of x = " ; cin >> x ; cout << " \n Please enter the value of y = ";

cin >> y ; xptr = &x; yptr = &y; if (xptr > yptr ) { cout << " \n x is greater than y "; } else { cout << "\n y is greater than x "; } getch(); }

Pointer with String For string character array is may be used char name [20]; name[0] = A ; name[1] = m ; name[2] = i ; name[3] = r ; Pointer, String and Arrays Is the initialization of the array complete? No, Character strings are always terminated by null character \0.

Therefore, we have to put the null character in the end of array. name[4] = \0 ; or char name[20] = Amir; Arrays must be at least one character space larger than the number of printable characters which are to Converting to lower Case letter void convertToUppercase (char *) ; main () { char s [30] = "Welcome To GC University" ;

cout << "The string before conversion is: " << s << endl ; convertToUppercase ( s) ; //function call cout<<"The string after conversion is: " << s ; getch(); } void convertToUppercase (char *sptr) { while ( *sptr != '\0' ) { *sptr = toupper ( *sptr ); //convert to uppercase character

sptr++; } } Pointer with String char myName[] = "Full Name ; char * myNamePtr = "Full Name"; Pointer with String main() { char a[]=Amir Ali";

char *b="government college lahore"; cout<

{ cout<<*b<

*destination++ = *source++; } *destination = \0; } Copying an array main() { char source[]="government"; int a=sizeof(source); char des[a]; copystring(source, des); cout<

getch(); } void copystring(char *source1, char *des1) { while(*source1!='\0') *des1++=*source1++; *des1='\0'; } Array of Pointers we initialize an array with a character string, the number of characters in the character string determines the length of array (plus one character to include the \0 character) eg. it is a single-dimensional array:

char name[] = My full name; The size of the name array is 13 char * myarray[10]; We read it as: myarray is an array of 10 pointer to character. If we take out the size of the array, it will become variable as: Array of Pointers char * myarray[] = {Amir, Jehangir}; Array of Pointers #include #include

main() { char *a[]={"safyan", ahmed"}; cout<<*a; cout<<*(a+1); getch(); } Pointers to Pointers We were doing double dereferencing to access the elements of a two-dimensional array by using array name (a pointer) to access a row (another pointer) and further to access a column element (of int data type).

In the case of pointer to pointer or double dereference, the first pointer contains the address of the second pointer, which contains the address of the variable, which contains the desired value. Double Pointer (De-reference) #include #include main() { char z='s'; char *a; char **b; a=&z;

b=&a; cout<<**b; getch(); } Multi-dimensional Array char multi[5][10]; muti+1 should take us to is pointing to the first element (col 0) of the second row (row 1). So by adding '1' in the array name, it has jumped the whole row or jumped over as many memory locations as number of columns in the array. The

width of the columns depends upon Type of the data inside columns. Here, the data type is 'char', which is of 1 byte. As the number of columns for this array 'multi' is 10, it has jumped 10 bytes. Multi-dimensional Array #include void main(void) { //To avoid any confusion, we have used int type below int multi[5][10]; cout << "\n The value of multi is: " << multi;

cout << "\n The value of *multi is: " << *multi; } Multi-dimensional Array we do double dereferencing like *multi'. If we want to go to, say, 4th row (row 3), it is achieved as 'multi + 3' . Once reached in the desired row, we can dereference to go to the desired column. Let's say we want to go to the 4th column (col 3). It can be done in the following manner. *(*(multi+3)+3)

Double Dereference main() { int a[3][3]={1,11,3,4,5,6,7,8,9}; cout<<*(*(a+1)+1); getch(); } void pointers The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties).

This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereference (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it. main () { char a = 'x'; int b = 1602; increase (&a,sizeof(a));

increase (&b,sizeof(b)); cout << a << ", " << b << endl; getch(); } void increase (void* data, int psize) { if ( psize == sizeof(char) ) { char* pchar; pchar=(char*)data; ++(*pchar); } else if (psize == sizeof(int) )

{ int* pint; pint=(int*)data; ++(*pint); } }

Recently Viewed Presentations

  • How was the Titanic Found? - I Love Science

    How was the Titanic Found? - I Love Science

    How was the Titanic located? Using sonar and submersibles. 1934 Dr. William Beebe reached a depth of 900 meters in a steel chamber called a Bathysphere ( fits 2 people). In 1960 a Swiss team of Auguste and Jacques Piccard,...
  • OB EMS E - University of Wisconsin Hospital and Clinics

    OB EMS E - University of Wisconsin Hospital and Clinics

    Documentation. Symptoms since LMP, genetic screening. Infection history, physical exam. Documentation. Additional notes for visit. ... Basic EMS kit will have essentials. Documentation. Record and document events as able. Most important times: infant birth time.
  • Windows Monitoring - Nagios

    Windows Monitoring - Nagios

    "Windows monitoring" What is it not? NSClient++! NSClient++ was written as a replacement for pNSClient. But it has evolved much since then. NSClient: Terminology. A quick note on the terminology. The word NSClient can mean many things depending on what...


    In a civil case for wrongful death brought by the surviving family members, a jury found that a . preponderance of the evidence . went against Simpson. ... DuressActing as a result of coercion or a threat of immediate danger...
  • The French-Indian War

    The French-Indian War

    North America in 1750 British French Fort Necessity Fort Duquesne * George Washington * Delaware & Shawnee Indians The Ohio Valley 1754 The First Clash Ben Franklin representatives from New England, NY, MD, PA Albany Congress failed Iroquois broke off...
  • Phy Section 2.1 Displacement &amp; Velocity

    Phy Section 2.1 Displacement & Velocity

    Times New Roman Arial Calibri Constantia Wingdings 2 Euclid Math Two Flow 1_Flow 2_Flow 3_Flow Primetime Phy Section 2.1 Displacement & Velocity PowerPoint Presentation Motion Frame of Reference Primetime Distance vs. Displacement Gecko's Displacement Displacement Velocity Formula Average Velocity Velocity...
  • Welcome to Back to School Night - Council Rock School District

    Welcome to Back to School Night - Council Rock School District

    Welcome to Back to School Night September 16, 2014 Tips for Parents Healthy snack and drink If you need to change your child's transportation for the day fill out form on website. If it occurs during the day e-mail
  • Lecture 13. Thermodynamic Potentials (Ch. 5)

    Lecture 13. Thermodynamic Potentials (Ch. 5)

    For such processes, the change of enthalpy is equal to the thermal energy ("heat") received by a system. Example: the evaporation of liquid from an open vessel is such a process, because no effective work is done. The heat of...