Question regarding pointers
Hey guys,
I have programmed a tree structure with the help of my C++ book and was wondering about the usage of double pointers by the author.
Here's the code:
Code:
#include <iostream>
#include <malloc.h>
#include <string>
using namespace std;
struct link_str{
string *pbegriff;
link_str *left;
link_str *right;
};
void eintragen(link_str **pstart, string s1){
link_str *pliste;
pliste = *pstart;
//First Case
if(pliste == NULL){
pliste = (link_str *)malloc(sizeof(link_str));
pliste->pbegriff = new string(s1);
pliste->left = NULL;
pliste->right = NULL;
*pstart = pliste;
return;
}
while(pliste != NULL){
if(s1 <= *(pliste->pbegriff)){
if(pliste->left != NULL){
pliste = pliste->left;
} else {
pliste->left =(link_str *)malloc(sizeof(link_str));
pliste = pliste->left;
//Datensatz
pliste->pbegriff = new string(s1);
pliste->left = NULL;
pliste->right = NULL;
pliste = NULL;
}
} else {
if(pliste->right != NULL){
pliste = pliste->right;
} else {
pliste->right =(link_str *)malloc(sizeof(link_str));
pliste = pliste->right;
pliste->pbegriff = new string(s1);
pliste->left = NULL;
pliste->right = NULL;
pliste = NULL; //Schleife zu Ende
}
}
}//while(pliste != NULL)
}//void eintragen(link_str **pstart, string s1)
void ausgabe(link_str *pliste){
if (pliste == NULL) return;
ausgabe(pliste->left); //Rekursion
cout << "Sorted: " << * (pliste->pbegriff) << endl;
ausgabe(pliste->right);//Rekursion
}
void freigeben(link_str *pliste){
if (pliste == NULL) return;
freigeben(pliste->left);
freigeben(pliste->right);
delete(pliste->pbegriff);
free(pliste);
}
int main() {
link_str *pstart = NULL;
string s1;
//Filling the list
do {
getline(cin, s1,'\n');
if(s1 != "QUIT"){
eintragen(&pstart,s1);
}
}while(s1 != "QUIT");
//output of the list
ausgabe(pstart);
//Free the list
freigeben(pstart);
pstart = NULL;
return 0;
}
My question:
1.Instead of writing eintragen(link_str **pstart,string s1) in line 13 which gets the value (&pstart, s1) in line 98, wouldn't it be enough if I just delete one & and one * and getting this:
eintragen(link_str *pstart,string s1) which just gets the value (pstart,s1).
Unfortunately the code doesn't work anymore, if I put it like that.
(Also, you have to change line 16 and 28 from *pstart to just pstart, as you only have to dereference once.)