簡體   English   中英

程序因strtok崩潰[C]

[英]Program crashes with strtok [C]

使用功能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);
 }

(對不起,我的英語不好^^)

問題是你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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM