Regarding errors you have in your code, the first one constructs a static number of MyStruct elements and store them in ms array, so ms is an array of MyStruct structures, of course in this you meant it to be of 2 elements only, later on you can't add any other element to ms array and though you have limited the number of MyStruct elements, while in the second case when you have a linked list you can chain as many MyStruct elements as you want and this will lead to dynamic number of MyStruct elements, the second case let you add as many MyStruct as you want during the run time, the second case should look like this conceptually in memory:
[ MyStruct#1 ] ----> [ MyStruct#2 ] ----> [ NULL ]
NULL though could be a MyStruct#3 for example, while the first one:
[ MyStruct#1 ] ----> [ MyStruct#2 ]
and that's it, no MyStruct#3 can be added.
Now let's go through the code you wrote:
struct MyStruct
{
int num;
} ms[1];
ms[1]
really means create me an ms array of one MyStruct element.
The code next assume you created two:
ms[0].num = 5;
ms[1].num = 15
Hence it should have been:
struct MyStruct
{
int num;
} ms[2];
And it will work fine! and keep in mind the simple illustration I made for it:
[ MyStruct#1 ] ----> [ MyStruct#2 ]
Second Case:
struct MyStruct
{
int num;
MyStruct *next;
};
MyStruct *ms = new MyStruct;
ms->num = 5;
ms->next = new MyStruct;
ms->next->num = 15;
This code uses the C++ operator new
if you save your source code as .cpp
you'll be able to compile as C++ application with no errors, while for C, the syntax should change like so:
struct MyStruct
{
int num;
MyStruct *next;
};
MyStruct *ms = (MyStruct *) malloc(sizeof MyStruct);
ms->num = 5;
ms->next = (MyStruct *) malloc(sizeof MyStruct);
ms->next->num = 15;
and don't forget to include #include <stdlib.h>
for the malloc()
function, you can read more about this function here.
And as the first case recall my illustration for the linked-list:
[ MyStruct#1 ] ----> [ MyStruct#2 ] ----> [ NULL ]
Where NULL is actually the next element of the ms->next MyStruct structure, to explain it more recall that ms->next is a pointer of MyStruct and we have allocated it a space in the heap so now it's pointing to a block of memory of the same size of MyStruct structure.
Finally here is a Stackoverflow question about when to use a linked-list and when to use an array so you can get exactly why people all around the world prefer linked-list sometimes and array other times.