1

每次我尝试使用 strtok() 时都会遇到分段错误。不知道为什么-我是 C 的新手。

这是我的代码:

#include "shellutils.h"
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    char input[150];

    while(1) {
        prompt();
        fgets(input, 150, stdin);

        char *fst_tkn = strtok(input, " ");

        printf("%s", fst_tkn);


        if(feof(stdin) != 0 || input == NULL) {
            printf("Auf Bald!\n");
            exit(3);
        }
    }
}

谢谢你的帮助!

4

1 回答 1

1

关于代码:

char *fst_tkn = strtok(input, " ");
printf("%s", fst_tkn);

如果您的input变量为空,或仅包含空格,fst_tkn则将设置为NULL. 然后,当您尝试将其打印为字符串时,所有赌注都已关闭。

您可以通过调整您给出的值在以下代码中看到input

#include <stdio.h>
#include <string.h>
int main (void) {
    char input[] = "";
    char *fst_tkn = strtok (input, " ");
    printf ("fst_tkn is %s\n", (fst_tkn == NULL) ? "<<null>>" : fst_tkn);
    return 0;
}
于 2013-08-13T08:57:04.317 回答