我试图用字符"|"标记argv,并分别为每个命令返回指针,例如:
如果argv = "./a ls -a '|' grep png"
,我需要cmd[0]
指向ls
,cmd[1]
指向grep
。我写了下面的代码,但不知何故,它只适用于第20行的一个无用的printf:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
char*** tokenizer(char** command, int argc){
int token_amount = 0;
char ***cmd = (char***) malloc(1 *sizeof(char**));
cmd[0] = &command[0];
for(int i = 0; i < argc; i += 1){
//For each founded '|', cmd receives the next position of command
if(!strcmp(command[i], "|")){
token_amount += 1;
cmd = realloc(cmd, token_amount *sizeof(*cmd));
cmd[token_amount] = &command[i + 1];
command[i] = NULL;
}
printf("n");
}
command[argc] = NULL;
return cmd;
}
int main(int argc, char** argv){
char **command, ***cmd = NULL;
//command doesn't receives the name of the executable
command = &argv[1];
cmd = tokenizer(command, argc - 1);
//Testing
for(int i = 0; i < 4; i += 1){
printf("%sn", cmd[i][0]);
}
//Testing
execvp(cmd[0][0], cmd[0]);
return 0;
}
我该如何避免这种打印?
这两行有问题:
cmd = realloc(cmd, token_amount *sizeof(*cmd));
cmd[token_amount] = &command[i + 1];
在调用realloc
之后,到cmd
的有效索引是0
到token_amount-1
。但是下一行使用token_amount
作为索引,这是越界的。您可能希望使用token_amount-1
作为索引。