0

Can someone please tell me if I am doing this right?

typedef struct {
    int *stk;
    int *sp;
} StackType;

I am supposed to define a StackType

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Looks fine to me (except the missing semi-colon on `sp`). Why are you asking? – paddy Feb 19 '14 at 01:32
  • 1
    What is `StackType` supposed to do? As for doing it right, more descriptive names and comments would be an improvement. – Potatoswatter Feb 19 '14 at 01:33
  • Welcome to Stack Overflow. Look at [Stack abstract data type in C](http://stackoverflow.com/questions/9212510/stack-abstract-data-type-in-c) for one set of ideas. That uses a linked list rather than array implementation for the stack. To the extent a design can be divined from the code you show, you look as if you're planning to use an array-based stack. However, you have no way in the structure to record the size of the stack, so you'll never know whether it is safe to push another value onto the stack. Syntactically, the code should compile, but that's not the only measure of 'rightness'. – Jonathan Leffler Feb 19 '14 at 04:04

1 Answers1

-1

This is absolutely correct.

And there are two options:

  1. always use struct keyword to define variables (struct MyStruct {...}; struct MyStruct myVar;)
  2. define a type in the way you do, define variables with just a type name (MyStruct myVar;);
clover
  • 4,910
  • 1
  • 18
  • 26
  • It wasn't my down-vote, but it could easily have been. A lot depends, I suppose, on what you mean by 'absolutely correct'. However, it is not obvious how the stack handling code would know how big the stack is, which is important for making sure there's no overflow or underflow of the stack. Syntactically, the code in the question will compile, but it cannot really be used safely. – Jonathan Leffler Feb 19 '14 at 04:00