我正在尝试读入一个文本文件,并逐字将其字符串添加到链接列表中。我是C语言新手,不太懂指针。我已经有几个不同的错误,只是搞乱了它,但现在我得到的分割错误在我的插入方法。这真的很令人沮丧。有人能解释一下我做错了什么吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct listNode { /* self-referential structure */
char data[50];
struct listNode *nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;
void insert(LISTNODEPTR *, char[]);
void printList(LISTNODEPTR);
char fpeek(FILE *);
main() {
FILE *fptr;
char file_name[20];
int nrchar = 0;
LISTNODEPTR startPtr = (struct listNode *) malloc(sizeof(struct listNode));
char word[50];
char c;
int i;
printf("What is the name of the file in which the text is stored?\n");
scanf("%s",file_name);
// printf("Type the number of characters per line");
//scanf("%d", &nrchar);
fptr = fopen(file_name,"r");
while(fpeek(fptr) != EOF) {
i = 0;
while(fpeek(fptr) != ' '){
word[i] = fgetc(fptr);
i++;
printf("%d", i);
}
word[strlen(word)] = '\0';
insert(&startPtr, word);
word[0] = '\0';
}
fclose(fptr);
printList(startPtr);
return 0;
}
/* Insert a new value into the list in sorted order */
void insert(LISTNODEPTR *sPtr, char value[])
{
LISTNODEPTR newPtr, currentPtr;
newPtr = malloc(sizeof(LISTNODE));
strcpy(newPtr->data, value);
newPtr->nextPtr = NULL;
currentPtr = *sPtr;
while(currentPtr != NULL){
currentPtr = currentPtr->nextPtr;
}
currentPtr->nextPtr = newPtr;
}
/* Return 1 if the list is empty, 0 otherwise */
int isEmpty(LISTNODEPTR sPtr)
{
return sPtr == NULL;
}
/* Print the list */
void printList(LISTNODEPTR currentPtr)
{
if (currentPtr == NULL)
printf("List is empty.\n\n");
else {
printf("The list is:\n");
while (currentPtr != NULL) {
printf("%s --> ", currentPtr->data);
currentPtr = currentPtr->nextPtr;
}
printf("EOF\n\n");
}
}
char fpeek(FILE *stream) {
char c;
c = fgetc(stream);
ungetc(c, stream);
return c;
}
最佳答案
首先,检查库函数(如fopen()等)的返回值。
其次,看西蒙斯的回答。
第三,在这个循环之后:
while(currentPtr != NULL){
currentPtr = currentPtr->nextPtr;
}
currentPtr->nextPtr = newPtr;
currentPtr为空,因此
currentPtr->nextPtr = newPtr;
将取消对空指针的引用。也许有点像
while(currentPtr && currentPtr->nextPtr) {
currentPtr = currentPtr->nextPtr;
}
currentPtr->nextPtr = newPtr;
更多的是你想要的。
最后,
char fpeek(FILE *stream) {
char c;
c = fgetc(stream);
ungetc(c, stream);
return c;
}
应该是
int fpeek(FILE *stream) {
int c;
c = fgetc(stream);
ungetc(c, stream);
return c;
}
总的来说
char fpeek(FILE *);
应该是
int fpeek(FILE *);