NightWish
NightWish

Reputation: 51

Pop function in a stack (C)

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.

Upvotes: 0

Views: 974

Answers (1)

MFisherKDX
MFisherKDX

Reputation: 2866

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);
}

Upvotes: 1

Related Questions