首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >strtok中的分段故障

strtok中的分段故障
EN

Stack Overflow用户
提问于 2011-11-12 00:36:10
回答 1查看 940关注 0票数 2

我一直收到这个错误。我很确定这与内存分配有关,但我不太确定如何修复它。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

char * VOWELS ="aeiouAEIOU";


void printLatinWord(char *a);


int main(int argc, char **argv){
    char phrase[100];
    char *word = malloc(sizeof(char) *100);

    printf("Enter the phrase to be translated: \n");

    fgets(word, 100, stdin);
    printf("The phrase in Pig Latin is:\n");
    word = strtok(phrase, " ");
    printLatinWord(word);

    return 0;
}

void printLatinWord(char *word){
    while (strchr(VOWELS, *word) == NULL){
    char consonant = *word;
    char *to=word, *from=word+1;

    while (*from)
         *to++=*from++;
         *to=consonant;
    }
    printf("%say\n", word);
}

输出结果是“分段故障(核心转储)”。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-12 00:39:01

代码语言:javascript
复制
fgets(word, 100, stdin);
word = strtok(phrase, " ");

你这里的参数是错误的。在未初始化的phrase中拆分字符串,然后将结果赋值给word,从而覆盖指向先前分配的内存的指针。

您可能打算让fgets将输入读入phrase,而不是word

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8097074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档