C++ - Double (2D) and Triple (3D) Pointers
Many programmers are not hesitating to use the pointers because of complexity and memory management. Nevertheless it is a powerful feature in C++ and gives more control to the programmers.
In this sample code, I have explained how to pass the get the array of values by using double pointers. When we pass the double pointer to get the array of values, it would become the triple pointer in the sub function.
strtok is built in library function that is used to tokenzie the strings using the separator. I have used space as a separater in strtok function. When you call strtok as first time you have to pass the first parameter as a valid pointer. The subsequent calls to strtok, first parameter would be NULL pointer.
Source Code
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int GetArrayOfValues(char *str, int *argc, char ***argvp)
{
if( str == NULL || strlen(str) == 0)
return -1;
char **argv = NULL;
char *p = new char[strlen(str) + 1];
char *token;
int token_count = 0;
// Count the number of elements
strcpy(p,str);
token = strtok(p, " ");
while(1){
if(token != NULL)
++token_count;
else
break;
token = strtok(NULL, " ");
}
*argc = token_count;
if( argc <= 0)
return -1;
// Allocate the memory
argv = new char*[token_count];
for(int i = 0; i < token_count; i++)
argv[i] = new char [100];
// Copy the elements
strcpy(p,str);
token = strtok(p, " ");
strcpy(argv[0], token);
for(int i = 1; i < token_count; i++)
{
token = strtok(NULL, " ");
strcpy(argv[i],token);
}
*argvp = argv;
delete p;
p = NULL;
return 0;
}
int main(int argc, char *argv[])
{
int c;
char **v = NULL;
int i;
if( GetArrayOfValues("ONE TWO THREE FOUR FIVE", &c, &v) < 0)
return 0;
std::cout << "Count : "<< c << "\n";
char buf[512];
for(int i = 0 ; i < c; i++)
{
sprintf(buf, "Array[%d] = %s\n", i + 1, v[i]);
std::cout << buf;
}
for(i = 0 ; i < c; i++)
{
delete v[i];
v[i] = NULL;
}
delete v;
v = NULL;
return 0;
}
Output
Count : 5
Array[1] = ONE
Array[2] = TWO
Array[3] = THREE
Array[4] = FOUR
Array[5] = FIVE
|