使用strtok时的Segfault

时间:2015-02-24 21:21:02

标签: segmentation-fault strtok

如果我注释掉“printPigWord(temp);”这个程序工作正常并且它会将这些单词标记为应该没有问题,但是一旦我将该行添加回去,它就不会执行下一个标记。它将打印1个“猪拉丁”字并返回主要,然后我得到分段错误。我不知道是什么原因造成的。

int main (void){
    char phrase[50];
    char *token, c, temp[20];
    int i=0;

    printf("Enter a phrase to be translated into pig latin: ");
    c = getchar();
    while( c != '\n'){
        phrase[i++] = c;
        c = getchar();
    }
    phrase[i] = '\0';

    token = strtok(phrase, " ");

    while(token != NULL){
        strcpy(temp, token);
        printPigWord(temp);
        token = strtok(NULL, " ");

    }

    return 0; /*Successful completion*/
}

void printPigWord(char token[20]){
    char first[1];
    char temp[20];

    /*save first letter */
    strncpy(first, token, 1);
    first[1] = '\0';

    /*add ay to end of first letter*/
    strcat(first, "ay");

    /*remove first letter of token*/
    strcpy(temp, &token[1]);

    /*add first letter+ay to end of token*/
    strcat(temp, first);

    /*print out token*/
    printf("%s\n", temp);

}

1 个答案:

答案 0 :(得分:0)

哼。首先只有一个字符长。你不能把东西连成它,否则你会覆盖别的东西(例如临时)......

first[1] = '\0'; // already out of boundes

/*add ay to end of first letter*/
strcat(first, "ay"); // again, first can carry only one char