首页 > 解决方案 > 将 char* 添加到 char**

问题描述

我正在尝试在 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;
  }

标签: c

解决方案


尝试类似:

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

或者更好的是,查看链接列表并使用它。


推荐阅读