程序崩溃与strtok [C]

时间:2018-04-26 14:42:54

标签: c list token strtok

我使用函数strtok()遇到了一些问题。 在本练习中,我的老师要求使用它来标记单个字符串,然后将单词保存在列表中,然后打印所有偶数标记及其出现次数。但是在写完输入字符串后程序崩溃了。有人可以解释我的问题在哪里吗?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define Dim 100

struct node{
int occ;
char sbuffer[Dim];
struct node *next;
}; 

struct node *first = NULL;

void occorrenze();
void insert(char *tkn);

int main(){

char array[Dim];
char buff[Dim];
char* token;

printf("Insert string: ");
gets(array);

for(token=strtok(array, " ") ; token!=NULL ; token=strtok(NULL," ") ){

    if ((strlen(token)%2)==0){
        insert(token);
        }

}

occorrenze();

 }

 void insert(char *tkn) {
 struct node *new_node;
 new_node = (struct node*)malloc(sizeof(struct node));
 strcpy(new_node->sbuffer, tkn);
 new_node->occ = 1;
 new_node->next = first;
 first = new_node;
 }

 void occorrenze() {
 struct node *p;
 struct node *s;
 for(p = first; p != NULL; p = p->next){    
     for(s = p; s != NULL; s = s->next){
         if(strcmp(s->sbuffer, p->sbuffer) == 0){
         p->occ++;
         }
      }
 }
 printf("\n%s\n%d\n",p->sbuffer, p->occ);
 }

(抱歉我的英文不好^^)

1 个答案:

答案 0 :(得分:2)

问题是printf()

末尾的occorrenze()
printf("\n%s\n%d\n",p->sbuffer, p->occ);

此时p为NULL,因为您的for循环已完成

for (p = first; p != NULL; p = p->next) {

您找到匹配的代码基本上是正确的,我只是稍微修改一下(您只需要一个循环)并将其移至insert()以便您不会如果单词已经在列表中,则必须再次添加该单词,然后occorenze()可以简单地遍历列表并打印单词及其occ值:

void insert(char *tkn) {
    struct node *new_node;
    new_node = (struct node*)malloc(sizeof(struct node));

    for (struct node *n = first; n != NULL; n = n->next) {
        if (strcmp(tkn, n->sbuffer) == 0) {
            n->occ++;
            return;
        }
    }

    strcpy(new_node->sbuffer, tkn);
    new_node->occ = 1;
    new_node->next = first;
    first = new_node;
}

void occorrenze() {
    for (struct node*n = first; n != NULL; n = n->next) {
        printf("%d %s\n", n->occ, n->sbuffer);
    }
}