简体   繁体   English

使用strtok进行C分段错误

[英]C Segmentation fault using strtok

I've created a program that is suppose to fully justify text which is input into the class except when transferring the words to output, errors are shown and I am unsure why but it ends up end up causing a segmentation fault when running the program. 我已经创建了一个程序,该程序可以完全证明输入到类中的文本的正确性,除非将单词转移到输出时,会显示错误,并且我不确定为什么,但是最终会在运行该程序时导致分段错误。 What is causing this error and how can I fix this? 是什么导致此错误,我该如何解决?

void format_text(int * option_stats, unsigned width, char * text)
{
    int x = 0, y = 0, spaces = 0, remain = 0, j = 0;
    char* words, output;
    char temp[200] = {" "};
    words = strtok(text, " ");
    while (words != NULL)
    {
        if (y + strlen(words) < width)
        {
            strcpy(temp, words);
            strcat(temp, " ");
            y += strlen(words) +1;
            spaces += 1;
            words = strtok(NULL, " ");
        }
        else if(y + strlen(words) ==  width)
        {
            strcpy(temp, words);
            printf("%s\n", temp);
            y = 0;
            spaces = 0;
        }
        else if(spaces > 1)
        {
            remain = width - (y - 1);
            j = remain % (spaces - 1);
            remain = (remain-j)/(spaces-1);
            output = strtok(temp, " ");
            while (output != NULL)
            {
                printf("%c", output);
                if(j > 0)
                {
                    printf(" ");
                    j--;
                }
                output = strtok(NULL, " ");
                y = 0;
                spaces = 0;
                words = strtok(NULL, " ");
            }
        }
        x += (strlen(words) + 1);
    }
}

You are using output as a char * in 您正在将output用作char *

while (output != NULL){

and

output = strtok(NULL, " ");

But output is declared as simple char 但是output被声明为简单char

char* words, output;

Take a look to Question 1.5 of C-FAQ 看看C-FAQ的问题1.5

变量outputchar类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM