Breaker Posted January 5, 2015 Share Posted January 5, 2015 Alright, I hate that big A word, so we will just call this a typeless stack. In C++ it was really simple, here on the other hand it is not so much. What are the pros and cons of using a typeless stack? Pros: Multiple data types Can use multiple data types on the same stack Easy way to manipulate data Works same way as system stack Cons: Annoying at times Difficult to manage More math involved So, let's get started with some structures. This tutorial assumes you know math, basic C, and pointers (as well as pointer arithmetic), if you do not please learn (or at least read) that before continuing. This is the hidden content, please Sign In or Sign Up Now, here is where it's really cool. We actually don't need to use a structure. Remember the SP is the only thing we use, and the programmer needs to ensure his stack is balanced at all times. If we keep these assumptions (we do), then all we need is a single pointer. Code: typedef void* Stack; But why even bother? Why not just use void *'s directly? Well, just for now we will use the typedef, for simplicity. Stack.h: This is the hidden content, please Sign In or Sign Up Now, why do we have that extra pointer? Well, if we assign it, we would be changing the value inside the function, but we just have a copy of that value (the address, for the trolls out there) so changing it will just result in a memory leak. If we have an address to the memory location storing the address, we can change it (double-pointer, or pointer-to-pointer). This is the hidden content, please Sign In or Sign Up Yeah, pointless one-liner, I will make this cleaner later on (you will see) This is the hidden content, please Sign In or Sign Up And even that is pretty small. Why are the functions so much smaller? Simple: it is a VERY basic type we are dealing with, and now we are hardly dealing with data at all. This is the hidden content, please Sign In or Sign Up And finally the most simple one: This is the hidden content, please Sign In or Sign Up But the question I ask myself is WHY IS THIS EVEN A C FILE... It just doesn't have enough crap there for me... I would rather use macros: This is the hidden content, please Sign In or Sign Up Now, we don't need to use double-pointers. If you notice, it is just a few things actually going on here. Some of our more advanced readers will probably be writing programs without these macros. This is the hidden content, please Sign In or Sign Up Isn't that neat? For some this may be too basic, but for others a stepping ground. Link to comment Share on other sites More sharing options...
Recommended Posts