1

嗨,我正在为我的一门课做一些事情。我

试图接收这个字符串数组,将其分解为 2 个数组并返回给调用者。我是 C 新手,所以如果你能帮忙,非常有帮助,谢谢……现在我收到编译警告,然后在我运行它时出现Segfault。

我一直在尝试很多事情,例如通过添加 * 和传递 &.. 来更改方法签名,但它似乎不起作用..

我做错了一堆东西...请帮助..我想要的是用 pList[0] = "less" 将 2 个数组返回给 main()

和 cList[0] = "ls" 和 cList[1] = "-t" ...从函数通过引用传入..

继承人我的代码到目前为止

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>

void makeLists(char **args, char*** parentList, char*** childList, int *childEnd, int *parentEnd) {
int i;
int foundPipeAt = 0;
int total = 0;

for(i = 0; i < 4; i++) {
    total++;
    if (strcmp(args[i], "|") == 0) {
        foundPipeAt = i;
    }

}

*parentList = malloc((foundPipeAt-1) * sizeof(char*));
*childList = malloc((total-(foundPipeAt)) * sizeof(char*)); 

printf("foundPipe %d\n", foundPipeAt);
for (i = 0 ; i < foundPipeAt ; i++ ) {
    *parentList[i] = (char *) malloc( (strlen(args[i])+1) * sizeof(char));
    *parentList[i] = args[i];
    printf("Parent List: %s\n", *parentList[i]);
}

// Set values for Parent end    
*parentEnd = foundPipeAt-1;
*childEnd = total-foundPipeAt;


int k=0;
for (i = foundPipeAt+1 ; i < total ; i++ ) {
    *childList[k] = malloc((strlen(args[i])+1)  * sizeof(char));
    *childList[k] = args[i];
    // This prints  correctly...
    printf("Child List:  %s\n", *childList[k]);
    k++;
}
}



main() {
int i;
char *args[4]; 
args[0] = "ls";
args[1] = "-t";
args[2] = "|";
args[3] = "less";

char **pList;
char **cList;

int parentEnd, childEnd;
makeLists(args, &pList, &cList, &childEnd, &parentEnd);
}
4

2 回答 2

3

错误消息 warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]是由缺少标头引起的。您需要stdlib.h在代码的开头添加。之后,一切都很好。

顺便说一句,尽管值本身是一个指针,但它是按值而不是通过 ref 传递的。

第二个问题是*parentList[i] = args[i];,可以使用strcpy(*parentList[i] , args[i]);。也这样做childList[i]

顺便说一句,您不需要三重指针,应该使用双指针。

于 2013-09-23T01:07:24.113 回答
1
count [1]  [2]  [3] [4]
index [0]  [1]  [2] [3]
arg   [ls] [-t] [|] [less]

foundPipeAt 是管道的索引,但它也是父级的计数。

// foundPipeAt - 1 gives you 1 less than you need
*parentList = malloc((foundPipeAt-1) * sizeof(char*));

// total - foundPipeAt gives you 1 more than you need
*childList = malloc((total-(foundPipeAt)) * sizeof(char*));

// i < foundPipeAt loops 1 past the amount you allocated
for (i = 0 ; i < foundPipeAt ; i++ )
于 2013-09-23T17:36:26.833 回答