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

  • Machine Guarding History - eLCOSH

    Machine Guarding History - eLCOSH

    The guard shall be such that it does not offer an accident hazard in itself. 1910.212(a)(3) Point of operation guarding. 1910.212(a)(3)(i) Point of operation is the area on a machine where work is actually performed upon the material being processed....
  • Introduction to Business-to-Business (B2B) Marketing

    Introduction to Business-to-Business (B2B) Marketing

    Introduction to Business-to-Business (B2B) Marketing What Is Marketing? the process of planning and executing the conception (product), pricing, promotion, and distribution of ideas, goods, and services to create relationships that satisfy individual and organizational objectives."
  • Iteration in C (II)H&amp;K Chapter 5 -

    Iteration in C (II)H&K Chapter 5 -

    Counter loops revisited (1) In the previous lecture, we considered loops whose number of iterations was known at the time the loop started. We used a temporary variable which acts as a counter for us to be able to control...
  • Parent Information Night Subject Selections for 2020 Current

    Parent Information Night Subject Selections for 2020 Current

    Can be in the form of a test, application task, experimental investigation, scientific posters, essays and problem-solving tasks which usually take place over a number of consecutive lessons. ... At a Unit 3 and 4 level, VCAA is interested in...
  • Classical Drama How Tragic! Breaking the Law  Death

    Classical Drama How Tragic! Breaking the Law Death

    Ismene This is the punishment for breaking Creon's law. Public stoning Antigone prefers to follow these laws. The gods' laws (DAILY DOUBLE) Creon sentences Antigone to this, changing his mind about the original decree. To be locked in a stone...
  • JRC Visitors&#x27;Centre: May - Nov 2015

    JRC Visitors'Centre: May - Nov 2015

    The resources of IAEA, EC, US NRC and other cooperation programs are used for implementation of separate tasks concerned with training, improvement and maintaining of the personnel qualification ... The NTP is the document in practical use by ANRA and...
  • Software Architecture - California State University, Northridge

    Software Architecture - California State University, Northridge

    Documenting Software Architectures Outline Introduction Uses of Architectural Documentation Views Choosing the Relevant Views Documenting a View Documentation across Views Unified Modeling Language Summary Introduction The software architecture plays a central role in system development and the organization that produces...
  • Handling Human Cell Lines - Purdue University

    Handling Human Cell Lines - Purdue University

    BIO-RELATED WASTE MATERIALS: Dispose of in properly labeled water impervious autoclavable bags (usually red or orange bags). Do not over fill bags. Utilize proper personal protective equipment and wash hands after handling. Keep bags closed until they are ready to...