簡體   English   中英

使用strtok進行C分段錯誤

[英]C Segmentation fault using strtok

我已經創建了一個程序,該程序可以完全證明輸入到類中的文本的正確性,除非將單詞轉移到輸出時,會顯示錯誤,並且我不確定為什么,但是最終會在運行該程序時導致分段錯誤。 是什么導致此錯誤,我該如何解決?

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

您正在將output用作char *

while (output != NULL){

output = strtok(NULL, " ");

但是output被聲明為簡單char

char* words, output;

看看C-FAQ的問題1.5

變量outputchar類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM