1

我创建了一个程序,该程序应该完全证明输入到类中的文本,除了将单词传输到输出时,会显示错误,我不确定为什么,但它最终会在运行程序时导致分段错误。是什么导致了这个错误,我该如何解决这个问题?

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);
    }
}
4

2 回答 2

6

您正在output使用char *

while (output != NULL){

output = strtok(NULL, " ");

但是output被声明为简单char

char* words, output;

查看C-FAQ 的问题 1.5

于 2013-08-26T09:32:10.107 回答
-1

变量output的类型char

于 2013-08-27T03:58:00.583 回答