0

I'm trying to push a pointer of my element into the stack so it would return a pointer instead of the element.

Based on my limited understanding it's returning the element but not the pointer.

typedef struct Stack
{
    int capacity;
    int size;
    TLDNode* elements;
}Stack;


void push(Stack *S,TLDNode *element)
{

    S->elements = element;
    S->size = S->size + 1;
    return;
}



 Stack *S;
    S = (Stack *)malloc(sizeof(Stack));
    S->elements = ( TLDNode *)malloc(sizeof( TLDNode)*100);
    S->size = 0;
    S->capacity = 100;

    PUSHTOSTACK(tld->head, S);

void PUSHTOSTACK(TLDNode *root,Stack *S) {

    PUSHTOSTACK(S,root);

}

1
  • S->size = S->size + 1; can be simplified to S->size += 1; or even S->size++; Commented Oct 23, 2015 at 1:32

1 Answer 1

1

Your elements member of your stack struct has type TLDNode*, which is equivalent to an array of TLDNodes. What you want is an array of pointers to TLDNodes, so you need another * in there:

typedef struct Stack
{
    int capacity;
    int size;
    TLDNode** elements;
}Stack;

Technically this is just a pointer to a pointer to a TLDNode, but this is basically equivalent to an array of pointers, as demonstrated by the following code snippet:

TLDNode *node_array[10]; // Array of 10 pointers to TLDNodes
TLDNode **elements = node_array; // node_array is assignable to elements
Sign up to request clarification or add additional context in comments.

2 Comments

@FlyingAtom - You don't need to (and arguably shouldn't) cast the result of malloc in C. Try this: S->elements = malloc(sizeof(*S->elements)*100);
@FlyingAtom - You should really only ask one question per question.... But your types obviously don't match. They don't match because you're trying to replace the whole elements array with a single element. What you probably want to do is set the last element in the array to the given element. S->elements[S->size-1] = element;

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.