:?
Hello,
Recently I have started studying C and C++. Right now I am stuck, trying to understand call by reference methodology.
I have a small program that glues two strings to eachother.
I am trying to reprogram it using the call by reference mechanism.
How do I do this??
I have especially problems understanding "pointer to a pointer" **. Can somebody explain me what exaclt ** means, why you would use it?
Here is the program: (sorry for the Dutch function names)
// Headerfiles
#include <stdio.h> // prototype i/o functies
#include <string.h> // prototype string functies
#include <iostream.h>
// Prototyping
void string_invoer(char **);
void string_voeg_toe(char ** , char );
void string_concatenate(char *, char *, char **);
void main()
{
char *p1 = new char[1];
char *p2 = new char[1];
char *p3 = new char[1];
*p1 = *p2 = *p3 = 0; // init p1, p2, p3 as empty strings
string_invoer( &p1 );
string_invoer( &p2 );
string_concatenate(p1, p2, &p3);
printf("\nString1 : %s", p1);
printf("\nString2 : %s", p2);
printf("\nString1 + String2 : %s", p3);
delete[] p1;
delete[] p2;
delete[] p3;
getchar();
}
// input of characters until newline is entered
void string_invoer(char **p)
{
printf(" \nGive string : " );
char c;
while (c != '\n') //read till "enter"
{
cin.get(c); // use cin.get to read space, tabs
if (c!='\n') //don't add "enter" to the string
string_voeg_toe(p, c);
}
}
// add character c to string p
void string_voeg_toe(char **p, char c)
{
char *pt = new char[strlen(*p) + 2];
// copy original string to new memory location
strcpy( pt, *p);
// add new character
pt[ strlen(*p) ] = c;
pt[ strlen(*p) + 1 ] = 0;
delete[] p;
// use p as pointer for new string
*p = pt;
}
// 2 strings s1 and s2 put together
void string_concatenate( char *s1, char *s2, char **dest)
{
// reserve location for string s1, s2 and the end character
char *st = new char[strlen(s1) + strlen(s2) + 1];
strcpy(st, s1); //copy s1 in st
strcat(st, s2); //add s2 to st, result is st
delete[] dest
*dest = st;
}