我想显示链接列表中的所有主题(char *),但是我遇到了分段错误。
/* 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;
}
然后:
char **topics;
/* Get the topic names */
topics = get_topics();
/* Display all the topics */
while (*topics != NULL) {
printf("%s\n", *topics);
topics++;
}
答案 0 :(得分:2)
您的代码的主要问题是您无法估计仅提供指向它的指针的数组长度。虽然您的主要错误是您没有为主题数组分配空间,但您的解决方案可能仍然无法在某些环境中运行。指针数组的解决方案非常简单。您只需明确地将最后一个元素设为NULL
。例如,对于整数,您需要使用一些特殊值来指示和数组(例如,最大或最小的int值)。
这是您的问题的代码:
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;
}