列出句子中的单词时出现分段错误

时间:2017-04-27 11:12:57

标签: c segmentation-fault

int getter2(char str[])
{
    int len=0;
    scanf("%100[^\n]s",str);
    while (str[len++] != '\0');
    return len-1;
}

int wordmaker(char str[],char word[15][15],int len)
{
    int i,temp=0,j=0;
    for (i=0;i<len;i++){
        if (((str[i]>='a') && (str[i]<='z')) || ((str[i]>='A') && (str[i]<='Z'))){
            word[j][temp++] = str[i];
        }
        else{
            j++;
            temp=0;
        }   
    }
    for (i=0;i<15;i++)
        for (j=0;j<15;j++)
            printf("%c",word[i][j]);

}

int main()
{
    char line[max],word[15][15];
    int len;
    printf("%d\n%s\n",getter2(line),line);
    wordmaker(line,word,len);

}

core dumped.segmentation fault.wordmaker功能有问题。我没有结束。当我运行程序时,我得到了正确放置的句子以及适当的长度。字库制作功能似乎是问题所在。 有人可以帮我调试吗。

1 个答案:

答案 0 :(得分:1)

我修复了代码中的一些问题并使其正常工作。但是有一个问题:如果你没有输入15个单词,它将打印垃圾(因为for (i = 0; i < 15; i++)中的wordmaker循环)。

一般要点:

  1. s的格式字符串中不需要scanf()
  2. wordmaker的返回类型应为void
  3. 为每个字符串添加了零终止字节。
  4. 打印字符串而不是单个字符。
  5. getter2内分配了lenmain的返回值。
  6. 代码中的所有内容:

    /* str.c
     * gcc -o str str.c -Wall
     */
    #include <stdio.h>
    
    /* As pointed by @BLUEPIXY, this should be 101 because of the format 
     * string of scanf. It will read 100 characters from stdin into the
     * string, but it doesn't take into account the terminating NULL byte.
     */
    #define max     101
    
    int getter2(char str[])
    {
        int len = 0;
    
        /* no need the trailing s in format string */
        scanf("%100[^\n]", str);
    
        while (str[len++] != '\0');
        return len - 1;
    }
    
    /* changed return type to void, since you're not returning anything */
    void wordmaker(char str[], char word[15][15], int len)
    {
        int i, temp = 0, j = 0;
        for (i = 0; i < len; i++) {
            if (((str[i] >= 'a') && (str[i] <= 'z'))
                || ((str[i] >= 'A') && (str[i] <= 'Z'))) {
                word[j][temp++] = str[i];
            } else {
                /* put the terminating null byte on each string */
                word[j][temp] = 0x0;
    
                j++;
                temp = 0;
            }
        }
        /* print the strings, not their characters
         *
         * If you use a loop to print characters, you need to have 15 byte
         * strings, otherwise you're gonna print garbage.
         */
        for (i = 0; i < 15; i++)
            printf("%s\n", word[i]);
    
    }
    
    int main()
    {
        char line[max], word[15][15];
        int len;
    
        /* here a little modification to initialize the variable 'len' */
        printf("%d\n%s\n", (len = getter2(line)), line);
        wordmaker(line, word, len);
    
    }
    

    作为旁注,如果您添加ctype.h,则可以更改((str[i] >= 'a') && (str[i] <= 'z')) || ((str[i] >= 'A') && (str[i] <= 'Z')) isalpha(str[i]),这更清晰。 isalpha() manual