Why does the following code display a blank linked list? I want to insert single characters to each node in the linked list. The characters are from the ch
string. It works fine when I change the node member sc
to integer and modify the associated code. But it seems there is an issue with using characters.
#include <stdio.h>
#include <string.h>
struct node {
char sc[1];
struct node *next;
};
char ch[30];
void insert(struct node **head_ref,int j) {
struct node *new_node = (struct node*)malloc(sizeof(struct node));
struct node *last = *head_ref;
new_node->sc[0] = ch[j];
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref=new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
return;
}
void display(struct node *head) {
struct node *t = head;
while (t != NULL) {
printf("%s", t->sc);
t = t->next;
}
}
main() {
FILE *fp;
fp = fopen("C:\\Users\\Jefferson Warie\\Desktop\\input.txt", "r");
if (fp == NULL) {
printf("File could not be opened.");
}
struct node *num1h;
num1h = NULL;
int i = 0, j;
char arr[100][30];
char ch[30];
while (!feof(fp)) {
fgets(arr[i], 31, fp);
i++;
}
for (i = 0; i < 2; i++) {
strcpy(ch, arr[i]);
for (j = 0; ch[j] != '\0'; j++) {
if (i == 0) {
insert(&num1h, j);
}
}
}
printf("First linked list: ");
display(num1h);
}