为什么以下代码显示空白链表?

时间:2017-09-17 12:33:37

标签: c string file linked-list char

为什么以下代码显示空白链表?我想将单个字符插入链表中的每个节点。字符来自ch字符串。当我将节点成员sc更改为整数并修改相关代码时,它工作正常。但似乎使用字符存在问题。

#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);
}

1 个答案:

答案 0 :(得分:0)

您已经声明了两次字符数组ch - 一次是全局变量,一次是main的本地变量。

此外,您需要添加#include<stdlib.h>才能使用malloc

这是最新更新的代码。

#include <stdio.h>
#include <string.h>
#include <stdlib.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;
    }
}

void 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];

    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);
}
相关问题