How do I find in C whether a stack is progressing in forward or reverse direction ? WIll this work?
int j = 0;
int k = 0;
if (&k > &j)
printf ("Stack is growing in forward direction");
else if (&k < &j)
printf ("Stack is growing in reverse direction");
To be reliable, one would have to find the difference between two function calls.
void func(int *p) {
int i;
if (!p)
func(&i);
else if (p < &i)
printf("Stack grows upward\n");
else
printf("Stack grows downward\n");
}
func(NULL);
Note that this won't give you an answer about C, but about your compiler.
You cannot. In your code, (&k > &j)
invokes undefined behavior behavior. Pointer comparison with relational operators is not defined unless the pointers point to objects within the same array (or one object beyond the end of the array).
Whether a stack exists is dictated by your implementation. Undefined behavior cannot predict implementation details.
The ISO C standard does not mention the word "stack" even once. A stack might not even exist. The memory used by function invocations to keep local variables might not even be contiguous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With