无法理解为什么一行最多只能有MAX_LINE / 2个字

时间:2019-04-06 16:39:19

标签: c

我的代码实际上是从用户那里获取文本输入的,然后令牌生成器通过标识空格将所有单词与输入分开。 它也做得更多,但这与我的问题无关。

我不明白为什么最大字数不能超过MAX_LINE / 2。 我的意思是为什么它必须为/ 2?

#define MAX_LINE 4096
#define MAX_WORDS MAX_LINE/2


void tokenize(char *line, char **words, int *nwords);
/* break line into words separated by whitespace, placing them in the 
   array words, and setting the count to nwords */

int main()
{
    char line[MAX_LINE], *words[MAX_WORDS], message[MAX_LINE];
    int stop=0,nwords=0;
int result, pid;
int status;
pid_t child, w;

    while(1)
    {
            printf("OSP CLI $ ");

    /* my code*/

    if (NULL==fgets(line , MAX_LINE, stdin))
    return 0;
    printf("%s",line);

    /* my code ends */

            /* read a line of text here */

            tokenize(line,words,&nwords);

    /* --Not using this code as i found my own---
    if (strcmp (words[0], "exit")==0)
    return 0;
    */
    if (strcmp(line,"exit") == 0) 
    break;

            /* More to do here */

    if (strcmp(words[0], "cd")==0)
    {
        result = chdir(words[1]);
    if (result < 0)
            {
                printf("No such file or directory\n");
            }
        }





    }
    return 0;
}


void tokenize(char *line, char **words, int *nwords)
{
    *nwords=1;

    for(words[0]=strtok(line," \t\n");
        (*nwords<MAX_WORDS)&&(words[*nwords]=strtok(NULL, " \t\n"));
        *nwords=*nwords+1
       ); /* empty body */
    return;
}

1 个答案:

答案 0 :(得分:2)

一行是由单词和分隔符(我想是空格)组成的,结尾是null。一行中可能包含最多单词的行看起来像

a a a a a\0

在此示例中,该行包含10个字符。有5个字。通常,N个字符不能超过N / 2个字。