链接列表,带参数的操作

我正在尝试实现程序,我可以动态创建〜任意数量的单链表,并对特定的列表执行操作(由参数定义)。 我创建了头指针的动态数组,以便我可以引用由paramater定义的某个头节点(数组的索引+ 1)。 参数只是(1,2,3 ……列表)。 到目前为止,我已经设法只实现初始化和推送function,但是在complilation之后的程序不能按预期工作。 问题出在哪儿?

#include  #include  #include  #define CHUNK 10 typedef struct { char *str; struct node *next; } node; node *initialise(node **array, int *amount_of_lists); void push(node **array, int *amount_of_lists); char *getString(void); int main() { node **heads = NULL; //initially null, pointer to the dynamic array of head pointers int amount_of_lists = 0; int *no_of_heads = &amount_of_lists; initialise(heads, no_of_heads); initialise(heads, no_of_heads); push(heads, no_of_heads); push(heads, no_of_heads); return 0; } node *initialise( node **array, int *amount_of_lists ) /*reallocate memory for another head pointer ans return the pointer to node*/ { ++(*amount_of_lists); printf("\n%d", *amount_of_lists); array = (node**)realloc(array, sizeof(node*)*(*amount_of_lists)); return array[(*amount_of_lists) - 1] = malloc(sizeof(node)); } int readParameter(int *amount_of_lists) { int parameter = 0, control = 0; bool repeat = 0; do { if(repeat) { printf("\nWrong parameter, try again."); } printf("\n Enter list parameter: "); control = scanf("%d", &parameter); fflush(stdin); repeat = 1; } while( control != 1 || parameter  (*amount_of_lists) ); return parameter; } void push(node **array, int *amount_of_lists) { int parameter = readParameter(amount_of_lists) - 1; node *temp = array[parameter]; array[parameter] = malloc(sizeof(node)); array[parameter] -> next = temp; array[parameter] -> str = getString(); } char *getString(void) { char *line = NULL, *tmp = NULL; size_t size = 0, index = 0; int ch = EOF; while (ch) { ch = getc(stdin); /* Check if we need to stop. */ if (ch == EOF || ch == '\n') ch = 0; /* Check if we need to expand. */ if (size <= index) { size += CHUNK; tmp = realloc(line, size); if (!tmp) { free(line); line = NULL; break; } line = tmp; } /* Actually store the thing. */ line[index++] = ch; } return line; } 

正如BLUEPIXY在他的评论1)中有些含糊地暗示,为了在initialise()修改main()heads ,你必须通过引用传递headsinitialise() ,即改变

  initialise(heads, no_of_heads); initialise(heads, no_of_heads); 

  initialise(&heads, no_of_heads); initialise(&heads, no_of_heads); 

所以

 node *initialise( node **array, int *amount_of_lists ) 

改变为

 node *initialise(node ***array, int *amount_of_lists) 

并且内部array更改为*array ,即

  *array = realloc(*array, sizeof(node *) * *amount_of_lists); return (*array)[*amount_of_lists - 1] = malloc(sizeof(node));