// Online C compiler to run C program online
i have tried to create a linked list and print the elements but its not working.could you please help me
// Online C compiler to run C program online
#include <stdio.h>
#include <stdlib.h>
struct sai{
int data;//data that needs to be stored
struct sai *ptr;//self pointer
};
void printplaces();
int main(){
struct sai *head;
struct sai *second;
struct sai *third;
struct sai *fourth;
head = (struct sai*)malloc(sizeof(struct sai));
second = (struct sai*)malloc(sizeof(struct sai));
third = (struct sai*)malloc(sizeof(struct sai));
fourth = (struct sai*)malloc(sizeof(struct sai));
(*head).data = 2;
head->ptr = second;
(*second).data = 2;
second->data = third;
(*third).data = 2;
third->ptr = fourth;
(*fourth).data = 2;
fourth->ptr = '\0';
printplaces(*head);
/*printf("%d\n",(*head).ptr);
printf("%d\n",(*second).ptr);
printf("%d\n",(*third).ptr);
printf("%d\n",(*fourth).ptr);
printplaces(*head);
}*/
}
void printplaces(struct sai *next){
for(int i = 0; i<= 2; i++){
printf("%d", next->data);
next = next -> ptr;
}
}
this line is wrong
second->data = third;
you mean
second->ptr = third;
and all the other places where you are trying to set the 'next' pointer
also
(*head).data = 2;
is better written
head->data = 2;
so you need
head->data = 2;
head->ptr = second;
second->data = 2;
second->ptr = third;
third->data = 2;
third->ptr = fourth;
fourth->data = 2;
fourth->ptr = '\0';