C and C++ hands-on tutorial derived data type pointer array and function null void pointer by examples
31 Pages

C and C++ hands-on tutorial derived data type pointer array and function null void pointer by examples

Downloading requires you to have access to the YouScribe library
Learn all about the services we offer


MODULE 8 DERIVED DATA TYPE - POINTERS Point to here, point to there, point to that, point to this, and point to nothing! But Oh N0000! they are just memory addresses!! My Training Period: hours Note: This Module may be one of the toughest topics in C/C++ that complained by students :o), although it is one of the most important topic. Abilities ▪ Able to understand and use pointers. ▪ Able to unde and use pointer operators. ▪ Able to understand, relate and use array and pointers. ▪ Able to understand, relate and use array, functions and pointers. ▪ Able to understand and use the main() command line arguments. ▪ Able to understand and use function pointers. ▪ Able to understand and use NULL and void pointers. ▪ Able to understand and use string and pointers. 8.1 What Is Pointers? - Pointers provide a powerful and flexible method for manipulating data in programs. - Some program routines can be more efficiently executed with pointers than without them, and some routines can be performed only with pointers. - To understand how to use pointers, a programmer must have a basic knowledge of how a computer stores information in memory. Pointers closely relate to memory manipulation. - Basically, a personal computer Random Access Memory (RAM) consists thousands of sequential storage locations, with each location being identified by a unique address. ...



Published by
Reads 49
Language English


MODULE 8 DERIVED DATA TYPE - POINTERS Point to here, point to there, point to that, point to this, and point to nothing! But Oh N0000! they are just memory addresses!!   My Training Period: hours   Notein C/C++ that complained by students :o), although it is one Module may be one of the toughest topics : This of the most important topic.   Abilities             Able to understand and use pointers.           Able to understand and use pointer operators.           Able to understand, relate and use array and pointers.           Able to understand, relate and use array, functions and pointers.   Able to understand and use themain()command line arguments.                   Able to understand and use function pointers.           Able to understand and useNULLandvoidpointers.           Able to understand and use string and pointers.   8.1     What Is Pointers?    Pointers provide a powerful and flexible method for manipulating data in programs. -- Some program routines can be more efficiently executed with pointers than without them, and some routines can be performed only with pointers. - To understand how to use pointers, a programmer must have a basic knowledge of how a computer stores information in memory. Pointers closely relate to memory manipulation. - personal computer Random Access Memory (RAM) consists thousands of sequentialBasically, a storage locations, with each location being identified by a unique address. Computer’s processor also has their own memory, normally called registers and cache. They differ in term of access speed, price and their usage. - addresses in a given computer, range from 0 to a maximum value that depends on theThe memory amount of physical memory installed. - Nowadays 128, 256 MB up to GB of RAM installed on the PCs are normal. - program runs on the computer and for processing data andComputer memory is used for storage, when instructions. - For example, when you use Microsoft Word program, it will occupy some of the computer’s memory.  In a very simple way, each program requires two portions of the memory that is: -1. Data portion –for data or operands. 2. The instruction code portion – what to do to the data such as operators etc.  Each portion is referred to as a memory segment, so there is: -1. A data segment (normally calleddatasegment). 2. An instruction code segment (normally calledtextsegment). - Now we just concentrate the memory storage for program data, the data segment. Details of the memory allocation story can be found inModuleWandModuleZ. - variable in a C/C++ program, the compiler sets aside a memoryWhen the programmer declares a location with a unique address to store that variable. -  the program uses the variable WhenThe compiler associates that address with the variable’s name. name, it automatically accesses the proper memory location. - The locations address remains hidden from the programmer, and the programmer need not be concerned with it. What we are going to do is to manipulate the memory addresses by using pointers. - Let say we declare one variable namedrate assign an initial value as follows: andof type integer int rate = 100; - and as an illustration, can be depicted asThen the variable is stored at a specific memory address follows:
Page 1 of 31
 Figure 8.1 - You can see, the memory address of the variablerate(or any other variable) is a number, so can be treated like any other number in C/C++. Normally the number is in hexadecimal format. - Then, if a variable’s memory address is known, the programmer can create a second variable for storing a memory address of the first variable. - From the above Figure, we can declare another variable to hold the memory address of variablerate; let say gives it a name,s_rate(Figure 8.2). - At the beginning,s_rate So,is uninitialized. storage has been allocated fors_rate, but its value is undetermined, as shown below.
 Figure 8.2 - Let store the memory address of variablerate, in variables_rate, so,s_ratenow contains the memory address ofratelocation in memory where the actual data (, which indicates its storage 100) is stored. - Finally, in C/C++ vocabulary,s_rateis pointing torateor is said a pointer torateand final illustration is shown below.
- In simplified form:
Figure 8.3
Figure 8.4 - of the pointer variable becomes something like this:So the declaration Page 2 of 31
_ int *s rate; - In other word, the variables_ratethe memory address of the variablecontains rateand is therefore a pointer torate asterisk (*) is used to show that is it the pointer variable instead of normal. The variable. - Thedefinitioncontains the memory address of another variable, where, the: A pointer is a variable that actual data is stored. -  From user side implicitly,By using pointers, it is an efficient way of accessing and manipulating data. it contains the actual location of your data, where the compiler can find that data in memory. - This is very useful for dynamic and efficient memory management programming as we know memory, registers and cache are scarce in computer system. - Why it is very efficient way? One of the reasons is because for every computer system, it is provided with fixed and limited amount of memory for temporary data storage and processing. - During the usage of computers, for example, the initialization of the Operating System and running programs (processes), there are loading and unloading data into and from the memory respectively, including the cache memory and the processors’ registers for temporary data storage and processing. This loading and unloading need an efficient memory management. - Furthermore some of the memory portion of computer system also used for shared data to further optimizes the utilization. - Apart from primary memory, secondary memory also involved in this memory management through swapping and paging. - applications such as real time processing, graphic manipulations and complexNewer computer mathematical calculations widely known for their memory intensive applications need storage efficiency to fully utilize the scarce computer memory. - usage of this fixed storage should be optimized.By using pointers, the - Yes, you can add extra memory module but without the usage ‘optimization’, it is not fully utilized somewhere, not sometime but most of the times:o). - with the dead blue screen? Pointers also generate many bugs in programs if used improperlyFamiliar or maliciously :o).   8.2 Pointers And Simple Variables   - A pointer is a numeric variable and like other variables, as you have learned before, must be declared and initialized before it can be used. - The following is a general form for declaring a pointer variable:   data type pointer variable name; * _ _ _   - For example:   char* x; int*type of car; _ _ float*value;    -data_typeis any valid C/C++ type. It is the pointer base type such aschar,intorfloat. It indicates the type of the variable’s data to which the pointer points. - pointer_variable_namefollows the same rules as other variables naming convention and must be unique. - From the above pointer declaration example, in the first line, the declaration tells us thatxis a pointer to a variable of typechar. - The asterisk (*) is calledindirection operator, and it indicates thatxis a pointer to typecharand not a normal variable of typechar the position of the. Note*, it is valid for all the three positions. - Pointers can be declared along with non pointer variables as shown below:   char *ch1, *ch2; //ch1andch2both are pointers to type char.   float *value, percent; //valueis a pointer to typefloat, and percent is // an ordinaryfloatvariable.   8.3 Initializing Pointers   
Page 3 of 31
- initialize the pointer, that is, make the pointer point toOnce a pointer is declared, the programmer must something. Don’t make it point to nothing; it is dangerous. - variables, uninitialized pointers will not cause a compiler error, but using an uninitializedLike regular pointer could result in unpredictable and potentially disastrous outcomes. - Until pointer holds an address of a variable, it isn’t useful. - C/C++ uses two pointer operators: 1. Indirection operator (*) – has beenexplained. 2. Address-of-operator (&) –meansreturn the address of. - When&placed before the name of a variable, the address-of-operator returns the memory address of the variable/operand. - For example: #include <stdio.h> #include <stdlib.h>   int main(void) { int *m;   int location = 200; m = &location;   printf("The data, *m = %d\n",*m); printf("The address where the data pointed to, m = %d\n", m); system("pause"); return 0; } Output: 
 - Therefore a pointer must be initialized with a statement that uses&operator as shown below: // declare a pointer variable, m of int type int *m; // assign the address of variablelocation // to variable m, so pointer m is pointing to // variablelocation m = &location; // the actual data assigned to variablelocation location = 200; - This statement means places the memory address of variablelocationinto variablem. The memory address refers to the computer’s internal location where the actual data is stored. What and where the address, is determined by the system. - In other word, pointer variablemreceives the address of variablelocationor the memory address of the variablelocationis assigned to pointer variablem. - rGpaihacll:y 
Page 4 of 31
Figure 8.5   -  * is a complement of &. Actually means returns the ItLet re-examine the indirection operator (*). value of the variable located at the address that follows. - From the previous example:   int *m; m = &location; location = 200; q = *m;   - Theq = *m; statement will place the actual data value stored in variablelocationinto variable q. That meansqreceives the actual data value stored at the memory address hold by variablemor the value stored in the variablelocationpointed to by variablem confused huh?. Very - The * operator appears before a pointer variable in only two places:   1. When declaring a pointer variable. 2. dereferencing a pointer variable (to find the data it points to).When   8.4 Using Pointers   - Only the addition and subtraction operations are permitted in expression involving pointers. - may be used on the right hand side of an assignment statement to assignAs with any variable, a pointer its value to another pointer as shown in the following example.   // program to illustrate the basic use of pointers //**********C++***************** #include<iostream> // using C header in C++ #include<cstdlib> using namespacestd;   void main() {  int num = 10, *point one, *point two; _ _  //declares an integer variable and two pointers variables    point one = &num; _  //assigns the address of variable num to pointer point one _    point two = point one; _ _  //assigns the (address) point one to point two _ _    cout<<"Pointers variables..."<<endl;  cout<<"*point one = "<<*point one<<"\n"; _ _  cout<<"*point two = "<<*point two<<"\n"; _ _       cout<<"\nNormal variable..."<<endl;  cout<<"num = "<<num<<"\n";       cout<<"\n-Both pointer point one and"<<"\n"; _  cout<<"-point two point to the same variable num."<<"\n"; _  cout<<"-That is why, they have same value, 10."<<endl;  // displays value 10 stored in num since point one _  // and point two now point to variable num _  system("pause"); } Output: 
Page 5 of 31
 -  memory address isprogram example can be illustrated graphically as shown below. TheThe arbitrarily chosen.
 Figure 8.6 - Notice the difference between memory address and actual data value, which stored at the memory address. Do not worry about the addresses, they are determined and provided by the system. - From the above example, we can: 1. Access the contents of a variable by using the variable name (num) and is called direct access. 2. Access the contents of a variable by using a pointer to the variable (*point_oneor *point two) and is called indirect access or indirection. _ - As conclusion, if a pointer namedpterof typeinthas been initialized to point to the variable namedvar, the following are true: int *pter; pter = &var; 3. *pterandvarboth refer to the contents ofvar(that is, whatever data value stored there). 4. pterand&varrefer to the address ofvar(thepteronly hold the address of variable varnot the actual data value). - name without the indirection operator (*) accesses the pointer value itself, which is ofSo, a pointer course, the address of the variable pointed to. Very confused :o). - Another example: //Basic pointer use #include <stdio.h> #include <stdlib.h>   void main() {  //Declare and initialize an int variable  int var = 34;  //Declare a pointer to int variable  int *ptr;    //Initialize ptr to point to variable var  ptr = &var;    //Access var directly and indirectly  printf("\nDirect access, variable var value = var = %d", var); Page 6 of 31
//you can use%pfor the pointer memory address directly or //%0xor%0Xin hexadecimal representative instead of //%d, just to avoid confusion here…  printf("\nIndirect access, variable var value = *ptr = %d", *ptr);    //Display the address of var two ways  printf("\n\nThe memory address of variable var = &var = %d", &var);  printf("\nThe memory address of variable var = ptr = %d\n", ptr);  system("pause ); " } Output: 
 - The address displayed for variablevarnot be 4094 on your system because different computermay will have different specification. - For pointer arithmetic operation, only two arithmetic operations, that is addition and subtraction available. For example: int age = 25; - So, C/C++ reserved storage for the variableageand store the value 25 in it. - Let say, C/C++ has stored this value at the memory address1000, and we declare a pointer variable namedptr_agethat point to the variableage. - Then after the following expressions have been executed: int *ptr age; _ ptr age = &age;  _ ptr age++; _ - The content of the pointer then becomes1002, not1001anymore (integer value takes two byte so C/C++ add 2 to the pointer). - occupy different amount of memory also depend on the platform used, whetherDifferent variable types 16, 32 or 64 bits. For example for 16 bits platform: int = 2 byte. float = 4 byte. - Each time the pointer is incremented, it points to the next integer and similarly, when a pointer is decremented, it points to the previous integer. - own address; so multibyte variable actually occupies severalEach individual byte of memory has it addresses. - used to handle the addresses of multibyte variables, the address of a variable is actuallyWhen pointers the address of the lowest byte it occupies. - For example: int = 12252; vint char = 90; vchar float = 1200.156004; vfloat - These variables are stored in memory as shown below.
Page 7 of 31
Figure 8.7
  - So:   1. intvariables occupy 2 byte starts at 1000. 2. charvariables occupy 1 byte starts at 1003. 3. floatvariables occupy 4 byte starts at 1006.   -  explained to you before, AsThen, how to declare and initialized pointers to these 3 variables? - Declaration - declare the pointer variables:   int *p vint; _ _ char *p vchar; _ float *p vfloat;   - the normal variables to the new pointer variables.Initialization - assign the addresses of   _ p vint = &vint; p vchar &vchar; = _ p vfloat = &vfloat; _   -  So:Then pointer is equal to the address of the first byte of the pointed-to variable.   _q ls1000. p vinte ua _eq als1003. p vcharu p vfloatequals1006. _    We have to understand this concept because we are dealing with addresses, not the actual data as -before. - arithmetic operation is called differencing, which refers to subtracting 2 pointers.Other pointer - same array can be subtracted to findFor example, two pointers that point to different elements of the out how far apart they are. - Pointer arithmetic automatically scales the answer, so that it refers to the array elements.  - Thus, ifptr1andptr2point to elements of an array (of any type), the following expression tells you how far apart the elements are:   ptr1 – ptr2;   8.5 Pointers Comparison   - that point to the same array.The comparison is valid only between pointers - Under this circumstances, the following relational operators work for pointers operation.   ==, !=, >, <, >=, and<=   - subscript, always have a lower address than theA lower array element that is those having a smaller higher array elements. - Thus ifptr1andptr2point to elements of the same array, the following comparison:   ptr1 < ptr2   isTRUE    - Ifptr1points to an earlier member of the array thanptr2does.
Page 8 of 31
- Many arithmetic operations that can be performed with regular variables, such as multiplication and division, do not work with pointers and will generate errors in C/C++. - The following table is a summary of pointer operations.   Operation Description You can assign a value to a pointer. The value should be an 1. Assignment (=) address with the address-of-operator (&) or from a pointer constant (array name) ndirection operator (*) gives the value stored in the pointed 2. Indirection (*) tToh leo ication. 3. Address of (&) pYooiun tcear,n  suos ey othu ec aadn dursees sp-ooif notepresr attoo rp otion ftienrsd.  the address of a 4. Incrementing You can add an integer to a pointer to point to a different memory location. 5. Differencing Ymoeum coarny  lsoucbattriaocnt . an integer from a pointer to point to a different 6. Comparison Valid only with 2 pointers that point to the same array.   Table 8.1: Pointer operations   8.6 Uninitialized Pointers   - Let say we declare a pointer something like this:   int *ptr;   - This statement declares a pointer to typeintbut not yet initialized, so it doesn’t point to anything known. - Then, consider the following pointer assignment statement:   *ptr = 12; // this is not an address lol!   - This statement means the value 12 is assigned to whatever addressptrpoint to. That address can be almost anywhere in memory. - may overwrite some important information, and the result can beThe 12 stored in that location anything from storage program errors to a full system crash. So, you must initialize a pointer so that it point to something. Do not create a stray pointer. - better solution may be you can assignA NULL(\0) value during the initialization before using the pointer, by pointing it to something useful or for pointer that point to a string you may just point to an empty string for dummy such as:   char * mystring ="";   - Program example:   #include <stdio.h> #include <stdlib.h>   int main() {   int *thepointer;   thepointer = NULL; //do some testing.... printf("The thepointer pointer is pointing to = %X\n", thepointer); printf("The thepointer pointer is pointing to %d\n", thepointer); = system("pause"); return 0; } Output: 
Page 9 of 31
    8.7 Arrays And Pointers   - arrays and this have been explained briefly inA special relationship exists between pointers and Module Array. - a pointer to the array’s first element. So,An array name without brackets is  if a program declared an arraydata[],data(array’s name) is the address of the first array element and is equivalent to the expression&data[0]references the address of the array’s first element.that means   data    equivalent to &data[0]or a pointer to the array’s first element.   - Thearray’s nameis, therefore a pointer to the array’s first element and therefore to the string if any. - A pointer is a constant. cannot  Itbe changed and remains fixed for the duration of program execution. - Many string operations in C/C++ are typically performed by using pointers because strings tend to be accessed in a strictly sequential manner. - Program example.   //Array, pointer and string #include <stdio.h>   void main() {  //an array variable of type char, sized 79  char sentence[80];    //prompt for user input...  printf("Enter a line of text:\n");  //read the user input...  gets(sentence);  //display what has been read by gets()  printf("Line of text entered: \n%s\n", sentence);  getchar(); } Output: 
- Graphically can be depicted as follows:
 Figure 8.8 - in sequential memory locations with the first element in the lowestElement of an array are stored address. - Subsequent array elements, those with an index greater than 0 are stored at higher addresses.
Page 10 of 31
- As mentioned before, array of typeintoccupies 2 byte of memory and a typefloatoccupies 4 byte. - So, forfloattype, each element is located 4 bytes higher than the preceding element, and the address of each array element is 4 higher than the address of the preceding element. - For example, relationship between array storage and addresses for a 6-elements int array and a 3-elementsfloatarray is illustrated below.
 Figure 8.9 - Thexvariable without the array brackets is the address of the first element of the array,x[0]. - The element is at address of1000; the second element is1002and so on. - of a particular data type, a pointer must beAs conclusion, to access successive elements of an array increased by thesizeof(data_type).sizeof()function returns the size in bytes of a C/C++ data type. Let take a look at the following example: //demonstrates the relationship between addresses //and elements of arrays of different data type #include<stdio.h> #include<stdlib.h>   voidmain() {        //declare three arrays and a counter variable        int i[10], x;        float f[10];        double d[10];          //print the table heading  printf("\nArray's el. add of i[x] add of f[x] add of d[x]");  printf("\n|================================");  printf("======================|");                //print the addresses of each array element        for(x=0; x<10; x++)  printf("\nElement %d:\t%p\t%p\t%p",x,&i[x],&f[x],&d[x]);  printf("\n|================================");  printf( =======|\n"); "===============  printf("\nLegends:");  printf("\nel.- element, add - address\n");  printf("\ndifferent pc, shows different addresses\n");  system("pause");  }   Output:   
Page 11 of 31