1

我有三个文件:header.h、machine.c 和 main.c

  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 回答