我正在尝试用 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/