Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 217
  • Last Modified:

Stack :Urgent...

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?
0
zizi21
Asked:
zizi21
  • 2
1 Solution
 
Infinity08Commented:
>> 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)
0
 
zizi21Author Commented:
thank you very much...
0
 
zizi21Author Commented:
thank you.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now