使用循环链接列表打印名称

时间:2015-04-12 09:17:43

标签: c linked-list

我正在研究循环链表问题并解决了它。但我遇到了其他问题。该程序获取循环链表节点中的人员名称并打印出来。

我的问题是,当且仅当名称为4个字符或更少时,程序才能正常工作。如果名称的长度超过4,则显示出奇怪的行为。

如果名称的长度是5个字符,那么程序将停留在启动函数的for循环的第二次迭代中。

如果名称的长度为6个字符或更多,则程序会立即终止显示输入的名称。

源代码是:

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define SIZE 10
#define NUM_PER_LINE 3

typedef struct node
{
 char name[SIZE];
 struct node * next;
} CListNode;

void get_name(char *a);
void print_list(CListNode *end_ptr);
CListNode *initiate(int n);
CListNode *insert_at_end(CListNode *first,CListNode *end_ptr, char *a);

int main(void) 
{
CListNode *list_end_ptr;

int n=6;
list_end_ptr=initiate(n);
print_list(list_end_ptr);

return 0;
}

void get_name(char *a)
{
 char *aa=(char *)malloc(10*sizeof(char));
 a=aa;
 scanf("%s", a);
}

CListNode *insert_at_end(CListNode *first,CListNode *end_ptr, char *a)
{
 CListNode *temp, *head=NULL;

 head=first;
 temp=(CListNode *) malloc(sizeof(CListNode));
 end_ptr->next=temp;
 strcpy(temp->name, a);
 temp->next=head;

 return temp;

}

CListNode *initiate(int n) 
{

 CListNode *end, *first=NULL,*ptr=NULL;
 int i;
 char new_name;
 end=(CListNode *) malloc(sizeof(CListNode));
 if (end==0) {
    printf("Allocation error...\n");
    exit(0); }
 end->next=end;

 for (i=0; i<n; i++) {
    if (i<1) {
        printf("Enter the name of the %d person: ", i+1);
        get_name(&new_name);
        strcpy(end->name, &new_name);
        first=end;
    }
    else
    {
        printf("Enter the name of the %d person: ", i+1);
        get_name(&new_name);
        ptr=insert_at_end(first,end, &new_name);
        end=ptr;
    }
 }

 return end;
}

void print_list(CListNode *end_ptr)
{
 int i=1;
 CListNode *str_ptr;
 if (end_ptr == NULL)
    printf("\n List is empty");
 else
 {
    str_ptr = end_ptr->next;
    while (str_ptr !=  end_ptr)
    {
        printf("%s \t", str_ptr->name);
        str_ptr = str_ptr->next;
        if (i%NUM_PER_LINE==0) {
            printf("\n");
        }
        i++;
    }
    printf("%s\n", str_ptr->name);
 }
}

1 个答案:

答案 0 :(得分:1)

问题在于您的get_name功能以及您使用它的方式。它的签名假定存储已经分配,​​因为你接受指针,而不是指针指针。您的代码完全忽略了分配;最重要的是,它传递一个指向角色的指针。

由于您在节点内分配name,请移除malloc,移除new_name,然后将name数组传递给get_name

void get_name(char *a) {
    scanf("%9s", a); // Limit the size to 9 chars
}
...
printf("Enter the name of the %d person: ", i+1);
get_name(end->name);