c++ - issues in understanding pointers -
the following codes book programming interviews exposed having problem understand concept of pointers. why can't use code no. 1.
code no. 1
bool insertinfront( intelement *head, int data ) { intelement *newelem = new intelement; if( !newelem ) return false; newelem->data = data; head = newelem; // incorrect! return true; } code no. 2
bool insertinfront( intelement **head, int data ) { intelement *newelem = new intelement; if( !newelem ) return false; newelen->data = data; *head = newelem; // correctly updates head return true; }
say calling function 1 as:
insertinfront(h, data); upon calling of function, computer makes duplication of arguments, release them when function returns. in code no.1, head=newelem assigned address of newelem head(which duplicate of h), released head, , address of newelem lost forever. in code no.2, however, function should called as:
insertinfront(&h, data); this means address of h duplicated head, , address of newelem assigned *head, i.e. head pointing, results in h. in way address of newelem after function returns.
Comments
Post a Comment