in C language. Provided the following broken implementation for push() onto a st
ID: 3596650 • Letter: I
Question
in C language. Provided the following broken implementation for push() onto a stick, fix the code. Hint: we are NOT looking for syntax errors here!
int push (Node **pTop, char *pNewString)
{
Node *pMem = NULL;
int success = 0;
pMem = (Node *) malloc ( sizeof (Node));
//initialize the node
//allocate dynmaic memory for the string --> pNewString
//note: pString is a feild in Node, which is a char *, not char []
pMem -> pString = (char *) malloc (sizeof (char) * (strlen (pNewString) + 1));
strcpy (pMem -> pString, pNewString);
pMem -> pNext = NILL;
//if memory was allocated
if (pMem != NULL)
{
success = 1;
pMem -> pNext = *pTop;
}
return success;
}
Explanation / Answer
int push(Node **pTop,char *pNewString)
{
Node *pMem = NULL;
int success =0;
pMem = (Node *)malloc(sizeof(Node));
//initialize the node
//allocate dynmaic memory for the string --> pNewString
//note: pString is a feild in Node, which is a char *, not char []
pMem -> pString = (char *) malloc (sizeof (char) * (strlen (pNewString) + 1));
strcpy (pMem -> pString, pNewString);
pMem -> pNext = NULL; // change NILL to NULL
//if memory was allocated
if (pMem != NULL)
{
success = 1;
pMem -> next = *pTop;
*pTop = pMem; // change the top of the stack to point to the pMem
}
return success;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.