c - While 循环清除我的数组? (C)

标签 c arrays string

我已经在这个问题上努力了一段时间,想知道是否有人能发现我做错了什么。我从 stdin 读取用户输入,分解他们通过 strtok() 输入的字符串,并将其存储到 char * 数组中。 char * 数组是在 while 循环外部定义的。

因此:用户通过 stdin 键入输入,数组中将填充命令中每个单词的字符串。

问题是,如果用户只是按 Enter 键,我希望数组保持它的值!我希望相同的值保留在数组中......这样我就可以重新执行相同的命令。看来 while 循环正在清除我的 char* 数组。代码如下:

char *commands[3];
char *result = NULL;
char delims[] = "     "; //a space AND a tab!
while (1) {

    printf(PROMPT);

    //Gathers user input!        
    char *input;
      char stuff[230];
      input = fgets(stuff, 230, stdin);

    printf("input has length %i\n", strlen(input));
    int helper = strlen(input);
    int i = 0;

    result = strtok(input, delims);
    printf("helper has length %i\n", helper);
    printf("commands[0] CHECK 1:%s", commands[0]);
    if (helper >1)
    {        
        while( result != NULL) 
        {
            printf("while gets hit!\n");
            if (i < 4)
            {            
                commands[i] = result;
                    result = strtok(NULL, delims );
                i++;    
            }
        }
    }


    printf("commands[0] is CHECK 2:%s", commands[0]);
    if (strncmp(commands[0], "step", 4) == 0)
    {
        lc3_step_one(p);
    }
    printf("commands[0] is CHECK 3:%s", commands[0]);
}      

如果用户按回车键,printf 的 CHECK 1、CHECK 2 和 CHECK 3 都不会打印任何内容。在他们最后输入“step”的情况下,我希望“step”保留在数组中,从而再次执行!

最佳答案

您正在使用指向 stuff 数组的指针填充命令数组。该数组每次都会被 fget 覆盖(可能用 null 替换第一个字符)。您需要将数据复制出来以保留它。

关于c - While 循环清除我的数组? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867078/

相关文章:

c - 在 C 中返回可变长度字符串的最佳实践

C - 函数的意外输出(基本/初学者代码)

python - 如何在字符串中查找正值或负值?

c - char指针的内存分配

javascript - 如何从数组上的 forEach 方法获取结果?

javascript - 使用 Object.keys 从 JavaScript 中的 JSON 文件中的值获取多维数组

python - 将数组切片为阶梯式连续 block 的 Python 方式是什么?

处理器的计算时间因执行而异,每次在 C 程序中使用 gettimeofday()

c - 如何编写一个程序来查找整型变量的最大值

C4477 - 格式字符串 '%s' 需要类型 'char *' ,但可变参数 1 的类型为 'int'