问题描述
在下面的代码中,我尝试使用printf和scanf从用户那里获取数据并将它们存储在我定义的称为节点的结构内。
该程序在第一个提示下正常运行,但是一旦用户输入名称,该程序就会以打印Age:salary:
结束有人可以帮我吗?
顺便说一句,还有谁能帮助我了解如何创建一个循环来将数据存储在各个节点中并将它们存储在一起吗? (不是一一地硬编码)
非常感谢您!
typedef struct node
{
char *name;
int age;
int salary;
struct node * next;
}node;
int main(void)
{
node *tmp = malloc(sizeof(node));
printf("Name:");
scanf("%s",tmp->name);
printf("Age:");
scanf("%i",&(tmp->age));
printf("salary:");
scanf("%i",&(tmp->salary));
tmp->next = NULL;
free(tmp);
}
解决方法
使用char []作为名称, 例如:
#include <stdlib.h>
#include <stdio.h>
typedef struct node
{
char name[128];
int age;
int salary;
struct node * next;
}node;
int main(void)
{
node *tmp = malloc(sizeof(node));
printf("Name:");
scanf("%s",tmp->name);
printf("Age:");
scanf("%i",&(tmp->age));
printf("salary:");
scanf("%i",&(tmp->salary));
tmp->next = NULL;
free(tmp);
}
如果要获得多个用户,请永远循环,并询问该用户是否要添加更多数据。 我已经创建了一个打印列表的功能
控制台:
Name:Foo
Age:12
salary:12
Continue Y/N
Y
Name:Bar
Age:14
salary:14
Continue Y/N
Y
Name:John
Age:30
salary:45
Continue Y/N
N
John,30,45
Bar,14,14
Foo,12,12
#include <stdlib.h>
#include <stdio.h>
typedef struct node
{
char name[128];
int age;
int salary;
struct node * next;
}node;
static void printList(node *n)
{
while (n) {
printf("%s,%d,%d\n",n->name,n->age,n->salary);
n = n->next;
}
}
static node *get_nodes(void) {
node *list = NULL;
while (42) {
char c;
node *tmp = malloc(sizeof(node));
printf("Name:");
scanf("%s",tmp->name);
printf("Age:");
scanf("%i",&(tmp->age));
printf("salary:");
scanf("%i",&(tmp->salary));
tmp->next = list;
list = tmp;
printf("Continue Y/N\n");
scanf(" %c",&c);
if (c == 'N')
break;
}
return list;
}
static void clearList(node *node) {
if (node->next) {
clearList(node->next);
}
free(node);
}
int main(void)
{
node *list = get_nodes();
printList(list);
clearList(list);
return 0;
}
,
要修复错误,应分配char *的内存。
第一种方法,当您创建结构时。
typedef struct node
{
char name[200]; // You specify that your char * can save 200 char
int age;
int salary;
struct node * next;
}node;
或者您可以创建init struct函数
node *init_node()
{
node *test = null;
test->name = malloc(sizeof(char) * 200);
test->age = 0;
test->salary = 0;
test->node = null;
return test
}
,
您正在尝试写入未初始化的内存
这是初学者经常遇到的问题。
您正在尝试使用char *name
声明存储名称。
这里的名称未指向有效的内存位置,这就是为什么您的程序未按预期运行的原因。
即使name
指向有效的内存地址,也必须分配足够的内存来存储数据。
您可以使用
#define BUFFER_SIZE 50
char name[BUFFER_SIZE];
您可以根据需要使用任何缓冲区大小,然后将长度为1的字符串存储在name
数组中。 -1
用于null termination character
\0
。
使用此声明,您正在分配BUFFER_SIZE
个字节的内存,而name
指向该数组中的第一个字节。
此分配发生在堆栈中,而不在HEAP中