1

I have the following linked list data structure:

struct _node {
    char *text;
    stuct _node *next;
}

I want to write a function that converts this linked list into an array of strings with each string being terminated by \n and the whole array terminated by \0.

For example, if the linked list was:

[first]->[second]->NULL

then the array should look like this:

[f][i][r][s][t][\n][s][e][c][o][n][d][\n][\0]

Here is my attempt:

char *convertToArray(struct _node *head){
    assert(head != NULL);

    int lines = findLines(head);
    int i = 0;
    struct _node *curr = head;

    char *textBufferArray = NULL; // return NULL if lines == 0
    textBufferArray = malloc(charCount(head) + lines + 1);
    // malloc enough memory for all characters and \n and \0 characters

    if (lines > 0){
        while (curr->next != NULL){
            strlcpy(textBufferArray[i], curr->text, strlen(curr->text)+1);
            // I need to add a new line here
            curr = curr->next;
            i++;
        }
    }

    I need to add \0 before returning
    textBufferArray[charCount(head) + lines] = '\0';

    return textBufferArray;
}
6
  • why don't you use a char pointer to array to store each string Commented Dec 24, 2016 at 16:13
  • Curious, why the sizeof(char) * which is just 1 *? Commented Dec 24, 2016 at 16:14
  • 2
    Note that what you are making is not an array of strings. It is an array of characters / one giant string. You may want to clarify your question. Commented Dec 24, 2016 at 16:14
  • @RaymondChen True, a string ends with a null character. OP seems to desire one string. Commented Dec 24, 2016 at 16:15
  • what is your question? Commented Dec 24, 2016 at 16:16

1 Answer 1

2

Considering you have malloced enough memory it is as simple as this

int i=0...
while(cur)
{
   int n =strlen(cur->S),k=0;
   while(n--)
     giant[i++]=cur->S[k++];
   giant[i++]='\n';
   cur=cur->next;
}
giant[i++]='\0';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.