我试图实现的代码是读取.txt文件并将字符串转换为节点的方法。基本上,当我读取.txt文件时,首先检查非字母(单词不能以数字开头,单词的任何索引中也不能有非字母数字)。一旦找到第一个字母,程序退出循环并进入另一个循环,直到看到一个空格。当我成功发表一个单词时(当发现有空格时,单词“结束”),我将该单词输入到链接列表中。总线错误:10从C中输入文本从.txt文件到节点
当我运行这个,我得到一个总线错误:10.我认为这将是由于单词[b]数组,但是当我malloc它,我仍然得到相同的错误。
预先感谢您!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define TRUE 1
#define FALSE 0
struct Node{
char value[100];
int numOccur;
int numVariance;
struct Node *next;
};
void testprint(struct Node * head){
int data;
data = head->value;
strcpy(data,head->value);
while(head != NULL){
printf("%s\n", data);
head = head->next;
}
}
int main()
{
struct Node *curr;
struct Node *n;
struct Node *head =0;
struct Node *tail =0;
struct Node *next;
char word[100];
int a;
int x;
FILE *file1;
file1 = fopen("test1.txt", "r"); //opens text file
if(file1 == NULL){
fprintf(stderr,"Error: Could not open file"); //if file1 has error, returns error message
exit(1);
}
a = fgetc(file1);
int b = 0;
while(a != EOF){
while(!isalpha(a)){
a = fgetc(file1);
continue;
}
n = (struct Node *) malloc(sizeof(struct Node));
while(isalnum(a)){
while(a != ' ' && a != EOF){
word[b] = a;
a = fgetc(file1);
b++;
}
word[b] = '\0';
}
n->next = 0;
if(head == 0){
head = n;
tail = n;
}
else{
tail->next = n;
tail = n;
}
}
testprint(head);
fclose(file1);
}
你的代码甚至没有编译。有很多错误。当期望Node *时,您可以使用FILE *调用testprint()。此外,当您执行word [b] =(char *)malloc(sizeof(char)* 30)时,数据类型不匹配。您正在分配一个动态字符数组(lhs)并将其分配给char(rhs)。 – Barney 2013-02-15 04:25:26
在这段代码中错误的东西中,'/ 0'不是终止的空字符; '\ 0'是。事实上,为了避免*再次出现问题,请不要使用* *。改用'0'。另外,当你到达你的第一个单词时,你的意图是分配一个新的30字符缓冲区*为永远的字符*?似乎有点矫枉过正,不是吗?特别是考虑到你将配置保存在一个无效的内存区域(类型错误)并且在过程中像筛子一样泄漏。把这个[codereview.stackexchange.com](http://codereview.stackexchange.com)并修复* real *问题。 – WhozCraig 2013-02-15 04:28:31