c - 将 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;
}
解决方案
尝试类似:
history[hisCounter] = calloc(MAX_CANON, sizeof(char));
strcpy(history[hisCounter], commandline);
或者更好的是,查看链接列表并使用它。
推荐阅读
- asp.net - Ajax Control Toolkit 在 Visual Studio 中有效,但在网站上无效
- mysql - 从旧数据库迁移数据,然后将其导入新数据库
- javascript - 如何更改 p5.js 中 2d 对象的 z 坐标?(和其他东西)
- python - 为什么第一页子框架的标签“lorem”显示在起始页上?
- c++ - __scrt_common_main_seh 是什么/在哪里?
- html - 超链接 ` ` 未调用映射的 Servlet。返回 404:找不到资源
- shopify - 如何删除与集合匹配的所有产品 - Shopify
- angular - Angular:测试用例失败 .focus 不是函数
- azure-web-app-service - 使用 webapps-deploy 部署到特定文件夹(不仅仅是 wwwroot)
- swiftui - 如何将文本与标签的文本而不是 SwiftUI 中的图像对齐?