1

こんにちは私は私のクラスの 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コードの先頭に追加する必要があります。その後、すべてが順調です。

ところで、値自体はポインターですが、参照ではなく値で渡されます。

2 番目の問題は*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 に答える