为什么下面的代码会显示一个空白的链表?我想向链表中的每个节点插入单个字符。这些字符来自 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);
}
最佳答案
你已经声明了字符数组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);
}
关于c - 为什么下面的代码会显示一个空白链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264125/