|< C & C++ Pointers 1 | Main | C & C++ Pointers 3 >| Site Index | Download |


 

 

 

 

 

MODULE 8a - MORE ON C/C++ POINTERS 2

Point to here, point to there, point to that, point to this, and point to nothing!

well, they are just memory addresses!!

 

 

 

 

My Training Period: xx hours

 

A continuation from previous Module. The source code for this module is: C/C++ pointers program source codes. The lab worksheets for your practice are: C/C++ pointers part 1 and C/C++ pointers part 2. Also the exercises in the Indirection Operator lab worksheet 1, lab worksheet 2 and lab worksheet 3.

 

The C and C++ pointers programming skills:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

8.7   Arrays And Pointers

  • A special relationship exists between pointers and arrays and this have been explained briefly in Array Module.

  • An array name without brackets is a pointer to the array’s first element.  So, if a program declared an array data[ ], data (array’s name) is the address of the first array element and is equivalent to the expression &data[0] that means references the address of the array’s first element.

data  equivalent to &data[0] or a pointer to the array’s first element.

  • The array’s name is, therefore a pointer to the array’s first element and therefore to the string if any.

  • A pointer is a constant.  It cannot be 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.

  • A 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...secure version is gets_s()

       gets(sentence);

       // display what has been read by gets()

       printf("Line of text entered: \n%s\n", sentence);

       getchar();

}

 

Output:

 

C C++ pointer array and string

  • Graphically can be depicted as follows:

C C++ pointer array and string

Figure 8.8

C C++ pointer and array size

Figure 8.9

// demonstrates the relationship between addresses

// and elements of arrays of different data type

#include <stdio.h>

 

void main()

{

       // 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");

}

 

Output:

 

C C++ pointer array and data size

12FEB412FEB0 = 4 bytes for int

12FE7812FE74 = 4 bytes float

12FE2412FE1C = 8 bytes double

// demonstrates the use of pointer arithmetic to access

// array elements with pointer notation

#include <stdio.h>

#define   MAX  10

 

void main()

{

       // declare and initialize an integer array

       int array1[MAX] = {0,1,2,3,4,5,6,7,8,9};

       // declare a pointer to int and an int variable

       int *ptr1, count;

       // declare and initialize a float array

       float array2[MAX] =  {0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9};

       // declare a pointer to float

       float *ptr2;

       // initialize the pointers

       // just an array name is the pointer to the

       // 1st array element, both left value and right value

       // of the expression are pointers types...

       ptr1 = array1;

       ptr2 = array2;

       // print the array elements

       printf("\narray1 values  array2 values");

       printf("\n-------------------------");

       // iterate or loop the arrays and display the content...

       for(count = 0; count < MAX; count++)

              printf("\n%d\t\t%f", *ptr1++, *ptr2++);

       printf("\n-------------------------\n");

    }

 

Output:

 

C C++ pointer arithmetic and array data size

*(list)  ==  list[0]             // first element

*(list + 1) == list[1]        // second element

*(list + 2) == list[2]        // third element

   ...

   ...

*(array + n) == list[n]      // the nth element

8.8    Arrays Of Pointers

int    *arrayPtr[20];

// assign the address of variable var to the first arrayPtr element

arrayPtr[0] = &var;

C C++ array of pointers

Figure 8.10

*arrayPtr[0]

viewArray(arrayPtr);

// a program that passes a pointer array to a function

#include  <iostream>

using namespace std;

 

// a function prototype for viewArray

void viewArray(int  *[ ]);

 

void main()

{

       // declare and initialize the array variables...

       int i,*arrayPtr[7], var[7]={3,4,4,2,1,3,1};

       // loop through the array...

       for(i=0; i<7; i++)

       // arrayPtr[i] is assigned with the address of var[i]

       arrayPtr[i] = &var[i];

       // a call to function viewArray,

       // pass along the pointer to the

       //1st array element

       viewArray(arrayPtr);

       cout<<endl;

}

 

// an arrayPtr is now passed to parameter q,

// q[i] now points to var[i]

void viewArray(int *q[ ])

{

       int  j;

      

       // displays the element var[i] pointed to by q[j]

       // followed by a space.  No value is returned

       // and control reverts to main()

       for(j = 0; j < 7; j++)

              cout<<*q[j]<<" ";

  }

 

Output:

 

C C++ pointer array and function console output

-----------------------------------------------------------------------------------------------

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

8.9    Pointers To Pointers

C C++ pointer to pointer illustration

Figure 8.11

C C++ pointer to pointer double pointer

Figure 8.12

int    **SecondPtr;

char	chs;            /* a normal character variable */
char	*ptchs;         /* a pointer to a character */
char	**ptptchs;      /* a pointer to a pointer to a character */

C C++ double pointer commad line argument

Figure 8.13

chs = 'A';

ptpch = &chs;

ptptpch = ptchs;

C C++ double pointer commad line argument

Figure 8.14

C C++ double pointer commad line argument

Figure 8.15

char    *ptptchs[ ] /* an array of pointer */

char    **ptptchs

int    main(int argc, char **argv)

int    main(int argc, char *argv[ ])

C:\>echo This is command line argument

This is command line argument

 

C C++ double pointer commad line argument

Figure 8.16

 

  1. argc (argument counter) is the number of arguments (unsigned integer), which we typed including the program name (that is equal to 0).

  2. argv (argument vector) is an array of strings (argv[0], argv[1], argv[2],...) holding each command line argument including the program name that is the first array element, argv[0].

int     main(int argc, char *argv[ ], *envp[ ])

 

/* a program to print arguments from command line */

/* run this program at the command prompt */

#include <stdio.h>

 

/*or int main(int argc, *argv[ ])*/

int main(int argc, char **argv)

{

int i;

printf("argc = %d\n\n", argc);

for (i=0; i<argc; ++i)

    printf("argv[%d]: %s\n", i, argv[i]);

return 0;

}

 

Output:

 

C C++ double pointer commad line argument: example

// pointer to pointer...

#include <stdio.h>

 

int main(void)

{

    int **theptr;

    int *anotherptr;

    int data = 200;

    anotherptr = &data;

    // assign the second pointer address to the first pointer...

    theptr = &anotherptr;

    printf("The actual data, **theptr = %d\n", **theptr);

    printf("\nThe actual data, *anotherptr = %d\n", *anotherptr);

    printf("\nThe first pointer pointing to an address, theptr = %p\n", theptr);

    printf("\nThis should be the second pointer address, &anotherptr = %p\n", &anotherptr);

    printf("\nThe second pointer pointing to address(= hold data),\nanotherptr = %p\n", anotherptr);

    printf("\nThen, its own address, &anotherptr = %p\n", &anotherptr);

    printf("\nThe address of the actual data, &data = %p\n", &data);

    printf("\nNormal variable, the data = %d\n", data);

    

    return 0;

}

 

Output:

C C++ double pointer output snapshot examples

 

8.10    Pointers and Function – Function Pointers

int	(*funptr)();

int    *funptr();

int	testfun(int x);
funptr = testfun;
/* calls testfun() with x as an argument then assign to the variable y */
y = (*funptr)(x);
typedef	int	(*funptr)();
funptr	testvar;

/* get the size of a function pointer */

unsigned    ptrsize = sizeof (int (*funptr)());

 

/* used as a function parameter */

void    signal(int (*funptr)());

/* invoking function using function pointer */

#include <stdio.h>

 

int somedisplay();

 

int main()

{

int (*func_ptr)();

/* assigning a function to function pointer

as normal variable assignment */

func_ptr = somedisplay;

/* checking the address of function */

printf("\nAddress of function somedisplay() is %p", func_ptr);

/* invokes the function somedisplay() */

(*func_ptr)() ;

return 0;

}

 

int somedisplay()

{

printf("\n--Displaying some texts--\n");

return 0;

}

 

Output:

 

C C++ function pointer

#include <stdio.h>

 

/* function prototypes */

void funct1(int);

void funct2(int);

/* making FuncType an alias for the type

'function with one int argument and no return value'.

This means the type of func_ptr is 'pointer to function

with one int argument and no return value'. */

typedef void FuncType(int);

 

int main(void)

{

FuncType *func_ptr;

/* put the address of funct1 into func_ptr */

func_ptr = funct1;

/* call the function pointed to by func_ptr with an argument of 100 */

(*func_ptr)(100);

/* put the address of funct2 into func_ptr */

func_ptr = funct2;

/* call the function pointed to by func_ptr with an argument of 200 */

(*func_ptr)(200);

return 0;

}

 

/* function definitions */

void funct1 (testarg)

{printf("funct1 got an argument of %d\n", testarg);}

 

void funct2 (testarg)

{printf("funct2 got an argument of %d\n", testarg);}

 

Output:

 

C C++ function pointer and argument

func_ptr = funct1;

(*func_ptr)(100);
func_ptr = &funct1;
(*func_ptr)(100);
func_ptr = &funct1;
func_ptr(100);
func_ptr = funct1;
func_ptr(100);

/* an array of pointers to function */

#include <stdio.h>

 

/* functions' prototypes */

int fun1(int, double);

int fun2(int, double);

int fun3(int, double);

/* an array of a function pointers */

int (*p[3]) (int, double);

 

int main()

{

int i;

/* assigning address of functions to array pointers */

p[0] = fun1;

p[1] = fun2;

p[2] = fun3;

/* calling an array of function pointers with arguments */

for(i = 0; i <= 2; i++)

(*p[i]) (100, 1.234);

return 0;

}

 

/* functions' definition */

int fun1(int a, double b)

{

printf("a = %d  b = %f", a, b);

return 0;

}

 

int fun2(int c, double d)

{

printf("\nc = %d  d = %f", c, d);

return 0;

}

 

int fun3(int e, double f)

{

printf("\ne = %d  f = %f\n", e, f);

return 0;

}

 

Output:

 

C C++ array of pointer

 

  1. A pointer to the first array element and

  2. An integer specifying the number of elements in the array, the array size.

// pointer to a function

#include <iostream>

using namespace std;

 

//  function prototypes...

float minimum(float, float);

// (*ptr) is a pointer to function of type float

float (*ptr)(float, float);

 

void main()

{

   float x1, x2, small;

   // assigning address of minimum() function to ptr

   ptr = minimum;

   cout<<"\nEnter two numbers, separated by space:  ";

   cin>>x1>>x2;

   // call the function pointed by ptr small has the return value

   small = (*ptr)(x1, x2);

   cout<<"\smaller number is "<<small<<endl;

}

 

float minimum(float y1, float y2)

{

   if (y1 < y2)

                            return  y1;

   else

                            return y2;

}

 

Output:

 

C C++ pointer to function

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

C and C++ pointers further reading and digging:

 

  1. The source code for this module is: C/C++ pointers program source codes.
  2. The lab worksheets for your practice are: C/C++ pointers part 1 and C/C++ pointers part 2.
  3. Also the exercises in the Indirection Operator lab worksheet 1, lab worksheet 2 and lab worksheet 3.

  4. Check the best selling C / C++ books at Amazon.com.

 

 

 

 

 

 

 

 

 

|< C & C++ Pointers 1 | Main | C & C++ Pointers 3 >| Site Index | Download |


C and C++ Pointers:  Part 1 | Part 2 | Part 3 |