c - 将 char* 添加到 char**

标签 c

我正在尝试用 c 编写一个 shell,并试图将用户输入的内容放入一个字符串数组 (char **)。我的问题是,例如,如果用户输入“pwd”,然后在下一个循环中输入“ls”,那么历史记录中的两个元素都会变成 ls。任何帮助将不胜感激。

 char **history = calloc(MAXARGS, sizeof(char*)); //MAXARGS = 128
 int histCounter = 0;
 char *commandline = calloc(MAX_CANON, sizeof(char));

 while(go) {  //exits loop when you type exit

    if (fgets(buffer, BUFFERSIZE, stdin) != NULL) {
              len = (int) strlen(buffer);
        buffer[len-1] = '\0';   
        strcpy(commandline, buffer);
    }

  history[histCounter] = commandline;

  if(histCounter > 0) {    //just to see if they are different
        printf("%s\n", history[histCounter-1]);
        printf("%s\n", history[histCounter]);
    }   
  histCounter = histCounter + 1;
  }

最佳答案

尝试类似的东西:

history[hisCounter] = calloc(MAX_CANON, sizeof(char));
strcpy(history[hisCounter], commandline);

或者更好的是,查看链表并改用它。

关于c - 将 char* 添加到 char**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52584118/

相关文章:

c - 如何将参数传递给 C 语言中的 main() 函数?

c - 使用递归的简单移动平均线

c++ - C++ 中的结构

迭代计算黄金比例

有人可以给出这段代码的一些基本示例吗?

c - 卡在二维数组上,将指针插入文件中的字符串

c - 为ARM上的异常(exception)设置soft-fp的GCC?

c - C中的结构问题

mysql - 从 C API 调用 MySQL 存储过程时出现问题

c - 如何在函数之间跳转