我正在尝试将给定的 char 数组拆分为单独的字符串。我这样做是通过将每个单词的地址放入一个数组中,然后从地址中获取字符串进行打印。
所以我更新了我的代码,但现在程序在打印 numArgs 之后但在“test2”之前冻结。我不明白为什么。
----------------old code-----------------------
char* parseArgs(char* comPtr){
char *args[100] = {0};
char *token;
int i = 0;
token = strtok(comPtr, " ");
while(token != NULL){
args[i] = malloc(100);
args[i] = &token;
token = strtok(NULL, " ");
}
return *args;
}
char* args = parseArgs(comPtr);
int i = 0;
while(i < numArgs){
printf("arg%d: %s\n",i,&args[i]);
i++;
}
-----------------------end old code--------------------
------------------new code------------------------
int countArgs(char* comPtr){
char *token;
int i = 0;
token = strtok(comPtr, " ");
while(token != NULL){
i++;
token = strtok(NULL, " ");
}
return i;
}
char** parseArgs(char* comPtr){
printf("test1");
char** args = calloc(100, sizeof(char*));
char* token;
int i = 0;
while(token = strtok(comPtr, " ")){
args[i] = token;
}
printf("test2");
return args;
}
printf("ComPtr: %s\n",comPtr);
char* path = "/bin/";
//int pid = fork(); //pid always 0 so using pid = 1 to test
//printf("PID:%d",pid);
int pid = 1;
printf("PID:%d",pid);
if(pid != 0){
int numArgs = countArgs(comPtr);
printf("test1");
printf("NumArgs: %d\n",numArgs);
printf("test2");
char** args = parseArgs(comPtr);
int i = 0;
printf("test3");
while(i < numArgs){
printf("arg%d: %s\n",i,args[i]);
printf("test4");
i++;
}
}
else{
//waitpid();
}