Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get linked-list data to String array in C

I have this function where list is a pointer to a linked list. This is the list struct which contains nodes with data.

typedef struct node{
    char *data;
    struct node *next;
}NODE;
typedef struct list{
    NODE* head;
    char *id;
    struct list *next;
    int size;
}LIST;

My goal is to take every data from the list and return it as a **char. It looks like it works but the line where i do words = (char**) calloc(numOfWords*wordLength,sizeof(char)); I'm not sure if it's correct and how it works exactly. Can you see anything that is going wrong in my code and help me? Thanks.

char **reset_words(LIST *list){
    char ** words;
    int i = 0,j = 0,wordLength,numOfWords = list->size;
    NODE *p;
    for (p = list->head; p != NULL; p = p->next) {
        wordLength = my_strlen(p->data);
        words = (char**) calloc(numOfWords*wordLength,sizeof(char));
        for(int k=0;k < wordLength;k++){
            words[i][j] = p->data[k];
            j++;
        }
        i++;
    }
    return words;
}
like image 887
kyriakos0801 Avatar asked May 17 '26 17:05

kyriakos0801


1 Answers

After i looked at your code here are some changes:

  1. If your list is a correctly done linked-list and all nodes have the same size of data then you could simply do wordLength = strlen(list->head->data).
  2. Initialize words outside the loops. The way i did it should work.
  3. Since you have string you can simply do strcpy(words[i],p->data) to add the string to your words array.

Try this out let me know if it works.

char **reset_words(LIST *list){
    char ** words;
    int i = 0,j = 0,wordLength = strlen(list->head->data),numOfWords = list->size;
    NODE *p;
    words = (char **)malloc(numOfWords * sizeof(char *));
    for (int h=0; h<numOfWords; h++)
        words[h] = (char *)calloc(wordLength,sizeof(char));
    for (p = list->head; p != NULL; p = p->next) {
        strcpy(words[i],p->data);
        i++;
    }
    return words;
}
like image 174
Chris Costa Avatar answered May 19 '26 07:05

Chris Costa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!