-
linkedlist guidance
HI guys need some help with this is the code below correct and is this how you make/use linklists.
#include<stdio.h>
#include<conio.h>
int main()
{
struct linkedlist{
int a,b,c;
struct linkedlist *next_linkedlist;
};
clrscr();
struct linkedlist *ptr; /* pointer to structure */
/* of type linkedlist */
ptr->a=10; /* pointer points to first data member/variable a */
ptr->next_linkedlist->a=37; /* pointer now points to the next */
/* structure then it's first data member which is a */
printf("%d",ptr->a); /* output 10 */
printf("\n%d",ptr->next_linkedlist->a); /* output 37 */
getch();
return 0;
}
/* The identifier a has been used twice in the above code */
/* has it been used correctly, To create more lists would */
/* I do this in the outer most structure add more statements */
/* like so struct linklist *next1_linkedlist; */
/* struct linklist *next2_linkedlist; */
/* ... */
/* ... */
/* ... */
/* Therefor being able to use a,b,c over and over and... */
/* But if all these pointers point to abc how come there not */
/* overwriten */
thanks leaner(wanting to be master).
-
Don't put the structure definition inside main because than you can not create pointers to the structure inside other functions unless you pass them all in as arguements. This would be messy. It would be okay to declare a structure inside of a C++ style class however and make the linked list private.
Anyway you did the assignment of the data members close to correctly but you used the self referential pointer incorrectly. The pointer is supposed to reference a new node. This node must be defined (with dynamic memory allocation). The structure declaration itself is fine. You defined an instance of a pointer to the structure fine as well. Please read a full chapter on Advanced Data Types before attempting to write a linked list program. For a linked list you have to understand structures, pointers, dynamic memory allocation, and scope.