arrays - 结构数组只取 C 中的最后一个值
问题描述
我正在尝试制作一个简单的命令行界面,但我在解析命令时遇到了问题:
process_t 是一个结构,它包含要存储在变量 argv 中的参数的命令路径。
int parse_cmd(char* tokens[], process_t* commands) {
assert(tokens!=NULL);
assert(commands!=NULL);
int position = 0;
int commandNumber = 0;
for(int i=0; tokens[i] != NULL; i++){
if(is_reserved(tokens[i]) == 0 && tokens[i+1] != NULL) continue;
int end = is_reserved(tokens[i]) == 0 ? i+1 : i;
int argc = position;
int count = 0;
process_t newProcess;
char* argv[MAX_CMD_SIZE] = {NULL};
for(argc; argc < end; argc++) {
argv[count] = tokens[argc];
count = count + 1;
}
newProcess.path = tokens[position];
newProcess.argv = argv;
position = i + 1;
commands[commandNumber] = newProcess;
commandNumber = commandNumber + 1;
}
}
int main(int argc, char* argv[]) {
char path[MAX_LINE_SIZE];
char line[MAX_LINE_SIZE];
char* cmdline[MAX_CMD_SIZE];
process_t cmds[MAX_CMD_SIZE];
getcwd(path, MAX_LINE_SIZE);
while (1) {
printf("mini@shell:%s$ ", path);
scanf("%[^\n]%*c", line);
trim(line);
clean(line);
tokenize(line, cmdline);
parse_cmd(cmdline, cmds);
toString(cmds);
break;.
}
return -1;
}
输入: ls -l ; grep ^a
为什么数组只包含最后一次迭代的 argv 值?
输出 :
路径:ls => argv = {grep, ^a, (null)} 路径:grep => argv = {grep, ^a, (null)}
解决方案
您正在尝试使用 block-local array ,它为每个命令重新创建,更糟糕的是,在返回argv
后甚至不再存在。parse_cmd
必须使用具有足够生命周期的数组对象;你可以通过改变来做到这一点
char* argv[MAX_CMD_SIZE] = {NULL};
至
char **argv = calloc(end-position+1, sizeof *argv);
free
请注意,当不再需要时,您必须使用此对象。
另请注意,您忘记了return commandNumber;
from parse_cmd
; 没有它,你就无法知道找到了多少命令。
推荐阅读
- tensorflow - 使用 tf 梯度更新 keras 模型
- google-cloud-endpoints - Google Cloud Endpoints:使用 protobuf.Any 字段对消息进行转码
- jenkins - GitHub 拉取请求 - 状态检查标题
- r - R:将函数应用于数据框列表中的数据框列(在 lapply 内应用)
- python - Python脚本在heroku上成功部署,但出现应用程序错误
- python - 捕获雨水:蛮力方法中的错误
- r - 使用 dplyr 和 paste0 汇总和整理结果后没有返回记录
- javascript - 猫鼬等待承诺错误
- python - 添加数组字段 OperationalError
- perl - 如何使用 Perl 根据它们的差异结果将目录中的文件排序到不同的文件夹中