So, I am trying to create a linked List where i take in strings from user then add them to the list and then delete the data at position 2. But i am having trouble with scanf (clarified in the output section) and also in the printing section. Any help would be appreciated.
The code
#include <stdio.h>
#include <stdlib.h>
struct node {
char *data;
char *begin;
char *end;
char *posi;
struct node *link;
};
struct node *add_begin(struct node *head, char *data) {
struct node *ptr = malloc(sizeof(*ptr));
ptr->data = data;
ptr->link = head;
return ptr;
}
struct node *add_end(struct node *head, char *data) {
struct node *ptr = malloc(sizeof(*ptr));
ptr->data = data;
ptr->link = NULL;
if (head == NULL) {
return ptr;
} else {
struct node *temp = head;
while (temp->link != NULL) {
temp = temp->link;
}
temp->link = ptr;
return head;
}
}
void add_at_post(struct node* head, char *data, int pos){
struct node *ptr=head;
struct node *ptr2=malloc(sizeof(struct node));
ptr2->data=data;
ptr2->link=NULL;
pos--;
while(pos !=1){
ptr=ptr->link;
pos--;
}
ptr2->link=ptr->link;
ptr->link=ptr2;
}
void delete_post(struct node* head, int position){
struct node*current= head;
struct node*previous= head;
if(head==NULL){
printf("is empty\n");
}
else if (position==1){
head=current->link;
free(current);
current=NULL;
}
else{
while(position!=1){
previous=current;
current=current->link;
position--;
}
previous->link=current->link;
free(current);
current=NULL;
}
}
int main() {
struct node *head = NULL;
char *data;
printf("Print at begin");
scanf("%s",data);
head = add_begin(head,data);//print at beginning of list
printf("Print at end");
scanf("%s",data);
head = add_end(head, data);//print at end of list
printf("Print at Position 2");
scanf("%s",data);
add_at_post(head,data,2);//print at position 2
delete_post(head,2);
for (struct node *ptr = head; ptr; ptr = ptr->link) {
printf("%s\n", ptr->data);
}
return 0;
}
The Expected Output
Print at begin
xxx
Print at end
yyy
Print at Position 2
ZZZ
xxx
zzz
The output I get. It calls the first scanf but skips the other 2. Then ends the RUN.
Print at begin
xxx
Print at end
Print at Position 2
scanf("%s",data);You must initializedatato point to valid memory before this. Writing to a memory location you don't own invokes undefined behavior.char *datais not initialized. Your code has undefined behaviour.