We help IT Professionals succeed at work.

Stack :Urgent...

zizi21
zizi21 asked
on
Medium Priority
242 Views
Last Modified: 2012-05-06
Hi ,

I am having some problems with stacks. I am debugging it.

Is this the way to create stacks?

typedef struct numbers{
int num1;
int num2;
}NUM;

typedef struct stack
{
    NUM *rows;
    int n;
    int topofstack;
}STA;

in create function..

s->n=10;
s->topofstack=0;
s->rows=malloc(s->n*sizeof(NUM *));

in push function..

s->topofstack+=1;
s->rows[s->topofstack].num1=0;
s->rows[s->topofstack].num2=10


this is where i think the problem is ...
in the create function, i have malloced an array of pointers...
now here, do i malloc for an item ?or this is fine?
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2009
Commented:
>> s->rows=malloc(s->n*sizeof(NUM *));

should be :

        s->rows=malloc(s->n*sizeof(NUM));

You want to allocate room for n NUM objects.


You initially set the top of the stack to 0 ... But there are no elements on the stack yet, so maybe you should set it to -1. (make sure to properly check for this value, and interpret it as an empty stack)

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
thank you very much...

Author

Commented:
thank you.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.