【问题标题】:Printing Names using Circular Linked List使用循环链表打印名称
【发布时间】:2015-04-12 09:17:42
【问题描述】:

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

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

如果name的长度是5个字符,那么程序会停留在initial函数的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);
 }
}

【问题讨论】:

  • 它会由于溢出导致未定义的行为,并且您的代码中也存在内存泄漏。

标签: c linked-list


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多