what’s the difference between those pieces of code?
1)
struct MyStruct
{
int num;
} ms[2];
ms[0].num = 5;
ms[1].num = 15;
2)
struct MyStruct
{
int num;
MyStruct *next;
};
MyStruct *ms = new MyStruct;
ms->num = 5;
ms->next = new MyStruct;
ms->next->num = 15;
I’m probably a little confused about linked-lists and lists in general, are they useful to something in particular? Please explain me more.
Your first definition…
…creates a statically allocated array with a single element. You cannot change the size of the array while your program is running; this array will never hold more than one element. You can access items in the array by direct indexing; e.g.,
ms[5]would get you the sixth element in the array (remember, C and C++ arrays are 0-indexed, so the first element isms[0]), assuming that you had defined an array of the appropriate size.Your second definition…
…creates a dynamically allocated linked list. Memory for this list is allocated dynamically during runtime, and the linked list can grow (or shrink) during the lifetime of the program. Unlike arrays, you cannot directly access any element in the list; to get to the sixth element you have to start at the first element and then iterate 5 times.