web analytics

Pointer to Pointer in C++

Options

davegate 143 - 921
@2016-01-04 19:21:55

You can have a pointer to a pointer of any type. Consider the following:

char ch;  /* a character */
char *pch; /* a pointer to a character */
char **ppch; /* a pointer to a pointer to a character */

We can visualise this in Figure 1. Here we can see that **ppch refers to memory address of *pch which refers to the memory address of the variable ch. But what does this mean in practice?

 

Fig. 1 Pointers to pointers

Recall that char * refers to a NULL terminated string. So one common and convenient notion is to declare a pointer to a pointer to a string (Figure 2)

Fig. 2 Pointer to String

Taking this one stage further we can have several strings being pointed to by the pointer (Figure 3)

Fig. 3 Pointer to Several Strings

We can refer to individual strings by ppch[0], ppch[1], ..... Thus this is identical to declaring char *ppch[].

Example: Command Line Input

One common occurrence of this type is in C command line argument input which we now consider.

C lets read arguments from the command line which can then be used in our programs.
 

We can type arguments after the program name when we run the program.
 

We have seen this with the compiler for example
 

   c89 -o prog prog.c
 

c89 is the program, -o prog prog.c the arguments.
 

In order to be able to use such arguments in our code we must define them as follows:
 

   main(int argc, char **argv)
 

So our main function now has its own arguments. These are the only arguments main accepts. 

  • argc is the number of arguments typed -- including the program name.
  • argv is an array of strings holding each command line argument -- including the program name in the first array element.

A simple program example: 
 

Assume it is compiled to run it as args.
 

So if we type:
 

   args f1 “f2“ f3 4 stop!

The output would be: 


NOTE: 
     argv[0] is program name.
     argc counts program name
     Embedded ““ are ignored.
     Blank spaces delimit end of arguments.
     Put blanks in ““ if needed.

   argc = 6
 
   argv[0] = args
   argv[1] = f1
   argv[2] = f2
   argv[3] = f3
   argv[4] = 4
   argv[5] = stop!

#include<stdio.h>
 
main (int argc, char **argv)
{ 

  /* program to print arguments from command line */
  int i;
  printf(“argc = %d“,argc);

  for (i=0;i<argc;++i)
    printf(“argv[%d]: %s“, i, argv[i]);
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com