我写了一个简单的程序,包括链表。当我尝试在它创建的函数中显示链表时,它工作正常;但是,当我返回 main 并尝试显示它时,它无法正常工作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#define LEN 20
struct Node {
char word[LEN];
int count;
Node * next;
};
Node* build_linked_list (char array[][LEN], int N);
Node* make_ordered_copy (Node * head);
void print_list(Node * head);
int main()
{
#define NUMBER 10
char array[NUMBER][LEN]; // array which the words will be recorded
int N=6;
for(int a=0; a<N; ++a) strcpy(array[a], "test");
print_list(build_linked_list(array, N));
getchar();
return 0;
}
Node* build_linked_list (char array[][LEN], int N)
{
Node ndArray[N];
Node *head, *newnode;
head = &ndArray[0];
strcpy(head->word, array[0]); // writing the first element to the head
head->count = 0;
head->next = NULL;
for(int a=1; a<N; ++a) // writing the elements in a linked list
{
newnode = &ndArray[a];
strcpy(newnode->word, array[a]);
newnode->count = 0;
newnode->next = head; // first location now becomes second location
head = newnode;
}
print_list(head);
printf("Previous values were shown in build_linked_list\n");
return head;
}
void print_list(Node* head)
{
Node* traverse;
traverse = head;
while(traverse) // while traverse is not NULL
{
printf("\"%s\" with the frequency of %d\n", traverse->word, traverse->count);
traverse = traverse->next;
}
return;
}
在从 main 调用的 print_list 函数中调试时,“traverse->word”首先显示正确的值,但它不能正确打印它,然后它会更改为另一个值。