【问题标题】:How do I make a struct containing a dynamic array of strings in C?如何在 C 中创建一个包含动态字符串数组的结构?
【发布时间】:2013-06-24 16:04:12
【问题描述】:

我有三个文件: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);

我该如何解决这些问题?

【问题讨论】:

    标签: c arrays string dynamic


    【解决方案1】:

    你需要一个指针数组。

    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]
    

    【讨论】:

      猜你喜欢
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 2018-04-14
      • 2021-08-05
      • 1970-01-01
      • 2011-01-04
      相关资源
      最近更新 更多