4

I have a structure in C which contains an array on which I perform stack operations.

If the stack is full, I need to prevent pushing an element past the end of the array, and return an error condition.

Is it better style to include the size of the stack as an element of the structure, and pass that number of elements to the stack_push() function, or should I have a sentinel element at the end of the stack array?

OregonTrail
  • 8,594
  • 7
  • 43
  • 58
  • 1
    Use a size variable (explanations would be too long for comment) – deviantfan Apr 04 '14 at 21:16
  • I'd really enjoy reading some reasoning. Please feel free to put it in an answer and if I agree with the reasoning I may accept your answer. – OregonTrail Apr 04 '14 at 21:17
  • 1
    Consider C strings (characters arrays terminated with a `'\0'`) and C++ strings (mystically coded `char`, and a quickly retrievable length and may have embedded `'\0'`). Which is more versatile? Which is newer? At the end-of-the-day, it depends upon your goals. One is not _always_ better than the other. – chux - Reinstate Monica Apr 04 '14 at 21:44

2 Answers2

4

How are you going to implement your stack_push() function?

If it requires scanning to the end of the array looking for an empty slot to insert the pushed element into, then you need a sentinel value anyway (e.g., NULL, if the array contains pointer elements). But note that the algorithm is going to be O(N).

On the other hand, keeping track of the number of active elements within the array allows your algorithm to be O(1) for pushes (and also for pops). It also saves you the trouble of allocating one extra element in the array, which may be significant if it's an array of structs.

Generally speaking, most stack data structures are implemented using an array and a counter.

David R Tribble
  • 11,918
  • 5
  • 42
  • 52
1

What sentinel value would you use? Of course, you have to be sure that the caller of this function will definitely never use this value. It could be very confusing to debug if your function is stopping prematurely at a sentinel value that seems like a reasonable input.

For things like strings, it is easy to use a NULL to terminate because a string should never have a zero byte. However, if you start using sentinels in some places and not in others, it can start to get very confusing for developers that are trying to use your code.

I would say to use a size argument unless there is a VERY clear and obvious choice of sentinel, and probably not even then.

idfah
  • 1,328
  • 10
  • 16