This program is a different approach over the same old singly linked list. Instead of creating a single structure and keeping the pointer of the next node of the same type as a member of the structure, I here used three different structures, and a plain long nextaddress member in each to point the address of the next node, because pointers also do the same.
Each node also has a int flag member as the first item of the structure, and the data part resides at the end of the structure because of its variable length.
The three structures are basic extension of the built-in types, long, double and char. While accessing the structures, I first casted the address of the node as an int *, which gives me access to the flag without fully typecasting the address to a definite structure from the three.
Then analyzing the flag, various operations are done.
So here's my question. Can it be called a valid linked list? And moreover, is it even a valid data structure?
It is fine to do this as long as you have a means to tell which type each node contains, like the
flagvariable.It seems reasonable that you can assume that
flagandnextaddresswill be on the same struct offsets no matter which struct type you use. Although strictly speaking the C language does not guarantee this, I believe it will work in practice on any system out there.However, you cannot assume that
datais located at(uint8_t*)&my_struct + sizeof(int) + sizeof(long). This offset may vary between structues because of different alignment requirements.A more serious concern is pointer aliasing. You cannot take a pointer
struct* xand convert that to another pointer typestruct* y. It will compile, but this is a violation of the type rules in C and invokes undefined behavior (unless both structs have exactly the same members). Standard-compliant compilers that use aggressive optimizations (like GCC) will not compile such code as expected. (What is the strict aliasing rule?)To be on the safe side and to get better program design overall, I would recommend that you instead do this:
Where
datais allocated separately from a node. You get a chained linked list of sorts.