1

I have three files: header.h, machine.c, and main.c

  1. How do I create a struct containing a dynamic array of strings?
  2. How do I fill the strings using functions in machine.c?
  3. How do I print that dynamic array of string?

My header.h file:

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

I want to add a dynamic array of strings into variable words in that struct. My machine.c file looks like this:

 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;
        }
    }       
}

My main is like this to pass the array of string to the 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);

How do I solve these problems?

0

1 Answer 1

2

You need an array of pointers.

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.