我做了一個程序,它接受一個或多個文本文件,並以ASCII順序打印單詞內的出現次數,一個單詞可以是字母數字的任意組合。我使用了一個鏈表,並且出現了分段錯誤錯誤。這個程序爲什麼會出現分段錯誤錯誤
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <ctype.h>
#include <string.h>
struct words{
char *word;
int count;
struct words *next;
};
struct words *head = NULL;
struct words *createnode(char *n)
{
struct words *p;
if ((p = (struct words *) malloc(sizeof(struct words))) == NULL)
return(NULL);
strcpy(p->word, n);
p->next = NULL;
return(p);
}
struct words *insert(struct words *new)
{
struct words *prev, *temp;
int compare;
if (head == NULL)
return(new);
compare = strcmp(head->word,new->word);
if(compare > 0){
new->next = head;
return(new);
}
if(compare == 0){
head->count++;
return(head);
}
prev = head;
temp = head->next;
if(compare < 0){
while(temp != NULL && strcmp(temp->word,new->word) < 0){
prev = temp;
temp = temp->next;
}
}
new->next = temp;
prev->next = new;
return(head);
}
char *whiteSpace(char *buf){
int i;
for(i = 0; buf[i] != '\0'; i++)
{
if(!isalnum(buf[i]))
{
buf[i] = ' ';
}
}
return(buf);
}
int main(int argc, char *argv[]){
FILE *fp;
char buf[100];
int lineNum = 1;
char *token;
struct words *p;
const char s[2] = " ";
int i;
printf("test");
for(i=1;i<argc;i++){
fp = fopen(argv[i], "r");
if(fp == NULL){
perror(argv[i]);
}
while(fgets(buf, 99, fp) != NULL){
whiteSpace(buf);
token=strtok(buf, s);
while(token != NULL){
if((p=createnode(token)) == NULL){
fprintf(stderr, "%s, file %s, line %d: ran out of memory \n", token, argv[argc], lineNum);
return(1);
}
else{
head = insert(p);
}
token = strtok(NULL, buf);
}
lineNum = lineNum+1;
}
for(p = head; p!= NULL; p = p->next){
printf("%5d %s\n", p->count, p->word);
}
}
return(0);
}
您可以打開調試和點代碼中你看到了嗎? – Phani