Structure pointer parameter transfer in C++

typedef struct node
{
int n;
node *left;
}*tnode;

When passing parameters, be careful to use **

void init(node **nn);
int main()
{
tnode nna;
init(&nna);
cout<<nna->n<<endl;
return 0;
}
void init(node **nn)
{
*nn=(tnode)malloc(sizeof(node));
(*nn)->n=0;
(*nn)->left=NULL;
}

Because the * is just a formal parameter, and will not change the real value of this address.

Or use another method:

int main()
{
tnode nna,nnb;
init(&nna);

nnb=initb(nnb);
cout<<nna->n<<" "<<nnb->n<<endl;
return 0;
}

node* initb(node *nn)
{
nn=(tnode)malloc(sizeof(node));
nn->n=1;
nn->left=NULL;
return nn;
}

Return the node pointer back to change the value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324853431&siteId=291194637