1

I want to display all the topics (char *) from a linked list, but I'm getting a segmentation fault.

/* Scroll through the list and store the names in an array (topics)*/
char **get_topics() {
    struct Topic *aux;
    char **topics = NULL;
    int i = 0;

    aux = head;

    while(aux != NULL)  {
        topics[i] = aux->name;
        aux = aux->next;
        i++;
    }

    return topics;
}

And then:

char **topics;

/* Get the topic names */
topics = get_topics();

/* Display all the topics */
while (*topics != NULL) {
    printf("%s\n", *topics);
    topics++;
}
2
  • I don't do much C so I could be mistaken, but don't you need to allocate topics? Commented Mar 25, 2016 at 12:07
  • 1
    You don't have an array, you have a NULL poonter; saying topics[i] doesn't magically create an array out of thin air. You may want to look up dynamic memory allocation. Commented Mar 25, 2016 at 12:24

1 Answer 1

2

The main problem of your code is that you can't estimate the length of an array provided just a pointer to it. Although your main mistake is that you don't allocate space for topics array but your solution might still not work in some environments. Solution for pointer arrays is quite simple. You just make last element a NULL explicitly. For instance for integers you need to use some special value to indicate and of array (for example maximal or minimal int value). Here's a code for your problem:

char **get_topics() {
    struct Topic *aux, *trav;
    char **topics = NULL;
    int i = 0, counter = 0;

    aux = head;
    trav = head;

    // you need a length of array
    while (trav != NULL)
    {
        ++counter;
        trav = trav->next;
    }

    // allocate memory
    topics = malloc(sizeof(char*) * (counter + 1));

    while(aux != NULL)  {
        topics[i] = aux->name;
        aux = aux->next;
        i++;
    }
    topics[counter] = NULL; // make sure that the last element is NULL
    return topics;
}
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.