1

header.h、machine.c、main.c の 3 つのファイルがあります。

  1. 文字列の動的配列を含む構造体を作成するにはどうすればよいですか?
  2. machine.c の関数を使用して文字列を埋めるにはどうすればよいですか?
  3. 文字列の動的配列を出力するにはどうすればよいですか?

私の header.h ファイル:

typedef struct smp * alamat; 
typedef struct smp{
int jd;
int level;
char c[100];
char * words;   
alamat sibling;
alamat child;
}simpul;

その構造体の可変ワードに文字列の動的配列を追加したいと考えています。私の machine.c ファイルは次のようになります。

 void addChild(char c[], char *dosa, int n, simpul* s){
    int i;
    if(s != NULL){//simpul tidak kosong
        dosa = malloc(n * sizeof(char*));
        simpul* baru = (simpul*)malloc(sizeof(simpul));
        strcpy(baru->c,c);
        baru-> jd = n;
        baru->words = dosa;

        if(s->child == NULL){//tidak punya anak
            baru->child = NULL;
            baru->sibling = NULL;
            s->child = baru;
        }else if(s->child->sibling == NULL){//anak cuma 1
            baru->child = NULL;
            s->child->sibling = baru;
            baru->sibling = s->child;
        }else{//anak banyak
            simpul * terakhir = s->child;
            while(terakhir->sibling != s->child){
                terakhir = terakhir->sibling;
            }
            terakhir ->sibling = baru;
            baru->child = NULL;
            baru->sibling = s->child;
        }
    }       
}

私のメインは次のようなもので、文字列の配列をmachine.cに渡します。

impul * node = findSimpul(penanda,t.root);

        char *string = (char *) malloc( (n* sizeof(char)));
        for(k=0;k<n;k++){
            scanf("%s",&string[k]);
        }
        addChild(anak,string,n,node);

これらの問題を解決するにはどうすればよいですか?

4

1 に答える 1

2

ポインタの配列が必要です。

char **strings;

int nmemb = 1;
strings = calloc(nmemb, sizeof(*char));
strings[0] = calloc(your_str_len, sizeof(char));

// now you have allocated space for one string. in strings[0]

// let's add another
nmemb = 2;
strings = realloc(strings, sizeof(*char) * nmemb);
strings[1] = calloc(your_2nd_str_len, sizeof(char));
// now you are ready to use the second string in string[1]
于 2013-06-24T16:14:23.553 に答える