0

I am having some issues with my pop() function in this program. This is an implementation of stack as singly linked list, and as you can see the pop function has two arguments:

void pop(STACK *stack, char **name)

I am told to: allocate memory for name in the pop function and return the name or NULL using the **name argument. I have tried several things, yet I don't understand what this actually means, and also how to do that since the function doesn't return anything (void type). Generally I am having trouble understanding this **name argument, and why would be we even want to use that in the first place. Here is my code so far:

typedef struct _stack STACK;
typedef struct _sElem stackElement;

struct _stack{
    stackElement *head;
};

struct _sElem{
    char *name;
    stackElement *next;
};

//solved:
void pop(STACK *stack, char **name){
    if(stack == NULL || stack->head == NULL){
        printf("Stack is empty. \n");
    }else{
        stackElement *temp = stack->head;
        char **nodeName = malloc(sizeof(char*));
        char *tempName = temp->name;
        (*nodeName)=tempName;
        (*name) = (*nodeName);
        stack->head = temp->next;
        free(temp);
    }
}

int main(){
    STACK *myStack = NULL;
    char *tempName = NULL;

    push(myStack, "One");
    push(myStack, "Two");
    push(myStack, "Three");
    pop(myStack, &tempName);
    pop(myStack, &tempName);

    //free stack and tempName

    return 0;
}

I appreciate any help. Thanks.

1

1 Answer 1

1

Generally I am having trouble understanding this **name argument, and why would be we even want to use that in the first place.

Because in C all parameters are passed by value. So if you your function was defined as void pop(STACK *stack, char *name) instead and you assigned the value of name inside pop it would not be visible to the caller after pop returned.

Instead, if you define your function as: void pop(STACK *stack, char **name), then you can assign to *name so the caller has access to the new value.

For instance:

STACK *head = ...
char *name = NULL;
pop(head, &name);
if (name != NULL)
{
   fprintf(stdout, "Popped name: %s\n", name);
   free(name);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the explanation, do I also have to allocate memory for the name in the pop function as char *name = malloc(sizeof(char)) or something?
yep. but you need to allocate the correct size. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.