studying C for few months, I encounter some difficulties with the use of pointers when dynamically building a binary tree:
Given my code below:
typedef struct TNoeud
{
int data;
struct TNoeud *pFilsGauche;
struct TNoeud *pFilsDroit;
} TNoeud;
void insereData(int data, TNoeud **pRacine)
{
TNoeud *noeud=malloc(sizeof(TNoeud));
noeud->data=data;
noeud->pFilsDroit=NULL;
noeud->pFilsGauche=NULL;
while((*pRacine)!=NULL)
{
if(data<(*pRacine)->data)
{
pRacine=&(**pRacine).pFilsGauche;
}
else
{
pRacine=&(**pRacine).pFilsDroit;
}
}
if(pRacine==NULL)
{
*pRacine=noeud;
}
free(noeud);
}
And in the main:
int main(int argc, const char * argv[]) {
TNoeud *pRacine=malloc(sizeof(TNoeud));
pRacine->data=0;
pRacine->pFilsGauche=NULL;
pRacine->pFilsDroit=NULL;
pRacine=&noeudRacine;
insereData(4, &pRacine);
return 0;
}
I read the following topic https://stackoverflow.com/a/28637104/7866010 for the BAD_ACCESS, but in my case, the pointer is not at NULL, as pRacine is assigned at 0.
I read the following topic https://stackoverflow.com/a/15154553/7866010 , but it didn't help.
I also tried the declaration variant
(*pRacine)->data
found in this topic https://stackoverflow.com/a/346739/7866010 without any difference.
So my questions are :
[SOLVED with TNoeud noeud as pointer instead of local variable. I also changed pRacine in the main the same way] Why do the pointer
*pRacine == NULL
when I pass a pointer to an assigned value as parameter of
insereData(4, &pRacine) ?
[SOLVED the same way] Why does the debugger give me random values to pointers
[1] = 0x00007fff5fbff700)
and datas
(int) data = 1606416544)
I didn't willingly assigned ?
[SOLVED: by deleting the
if(pRacine==NULL)
condition and replacing it by just(*pRacine)=noeud;
] Now no more errors, but the result ofinsereData(4, &pRacine);
doesn't impact pRacine : it should be
pRacine->pFilsDroit->data==4
but here it remains at NULL. I don't understand why, as it's not a local variable anymore.
Thanks all for your answers!