【发布时间】:2020-04-06 19:21:38
【问题描述】:
我正在创建一个只有一个节点的单链表,但在让它按我想要的方式工作时遇到了一些麻烦。当我输入我想放在列表中的信息时,我会在不做任何事情的情况下将我的最后一条数据附加到前一个数据中。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#define maxName 30
#define maxID 10
#define maxAge 3
typedef struct node
{
char fName[maxName];
char lname[maxName];
char PUID[maxID];
char age[maxAge];
struct node *next;
}node;
node *head = NULL;
//This function will create a list with just a single node and the data to the list must be passed by paramter
node * createnode(char firstName[], char lastName[], char puid[], char age[])
{
head = (node*)malloc(sizeof(node));
printf("Enter the first name: ");
scanf("%s", &(head -> fName));
printf("Enter the last name: ");
scanf("%s", &(head -> lname));
printf("Enter the PUID: ");
scanf("%s", &(head -> PUID));
printf("Enter the Age: ");
scanf("%s", &(head -> age));
return head;
}
这是我输入信息时得到的输出: 杰克,托马斯,789456987525,25->
25 附加到我输入的 PUID 的末尾。任何帮助你都很棒!谢谢!
【问题讨论】:
-
如果你想在一个 char 缓冲区中存储一个 10 位的 id,该缓冲区应该是一个至少包含 11 个字符的数组,因为它需要一个作为空终止符。并且您应该强制用户输入的数字不能超过 10 位,否则缓冲区会溢出。这就是你的情况。
-
如果一个答案对你有帮助,你应该点击投票号下的勾号按钮。
标签: c linked-list scanf singly-linked-list c-strings