Trouble with stack implementation
Ok, I know this is probably a really stupid question but I have been try to figure out how my thinking is flawed for about half an hour. I'm so angry that I 'm probably not thinking straight. My program gets to a point, then crashes.
relevant code:
Stack.h:
Stack.c:
relevant code:
Stack.h:
Code:
typedef struct StackItem
{
[item]
struct StackItem * lower;
struct StackItem * higher;
} StackItem;
typedef StackItem * Stack;Code:
int pushOntoStack (Stack * pstack, [item])
{
StackItem * pnew;
pnew = (StackItem *) malloc(sizeof(StackItem));
if (pnew == NULL)
return 0;
(*pstack)->higher = pnew; /*This is where the program crashes*/
pnew->[item] = [item];
pnew->lower = *pstack;
pnew->higher = NULL;
*pstack = pnew;
return 1;
}
Is this supposed to be valid C? What are the random square brackets doing?
I'd say it's likely that *pstack is NULL. This would happen if you're pushing onto an empty stack. What you'd need to do is this:
Code:
if (*pstack)
(*pstack)->higher = pnew;akb825 Wrote:I'd say it's likely that *pstack is NULL. This would happen if you're pushing onto an empty stack. What you'd need to do is this:Gah! So simple!
Code:
if (*pstack)
(*pstack)->higher = pnew;
Thanks, it works now.
Is (*pstack) even a pointer to a memory address? How is the Stack type defined?
belthaczar Wrote:Is (*pstack) even a pointer to a memory address? How is the Stack type defined?thats called dereferencing a pointer, it returns the 'value' of the object given the pointer value.
Sir, e^iπ + 1 = 0, hence God exists; reply!
I don't think that's what he was asking. He was wondering if pstack, or what pstack was pointing to, was valid in the first place, and what exactly it's supposed to represent. From what I understand, (*pstack) is a pointer to the top of the stack, while he sent the address into the push function (to get pstack) so he could modify it. What I caught was that when the stack is empty, the top of the stack is NULL, which he was dereferencing. (judging from the times, belthaczar may not have seen ferum's post saying my fix worked before posting his)
Possibly Related Threads...
| Thread: | Author | Replies: | Views: | Last Post | |
| Previous frame inner to this frame (corrupt stack?) | wyrmmage | 9 | 6,441 |
Nov 29, 2006 05:14 PM Last Post: wyrmmage |
|

