【发布时间】:2013-04-10 16:59:21
【问题描述】:
我看过其他一些关于如何打印链接列表的帖子,但没有一篇对我有帮助,所以我决定发布我自己的代码。问题来了:
我可以完美地添加姓名和年龄,但第二次添加另一个姓名和年龄时,它会覆盖前一个。
所以如果我输入:
Matt 和 21,然后是 charles 和 34。它只会输出 charles 和 34。 如何让它输出所有内容? 预先感谢您的帮助! :)
这是我的代码:
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define pause system ("pause")
// prototype variables
struct node * initnode(char*, int);
void printnode(struct node*);
struct node{
char name[20];
int age;
struct node *next;
};
struct node *head = (struct node*) NULL;
struct node *end = (struct node*) NULL;
struct node* initnode(char *name, int age){
struct node *ptr;
ptr = (struct node*) calloc(3, sizeof(struct node));
if(ptr == NULL)
return (struct node*) NULL;
else {
strcpy(ptr->name, name);
ptr->age = age;
return ptr;
}
}
void printnode(struct node *ptr) {
printf("Name -> %s\n", ptr->name);
printf("Age -> %d\n", ptr->age);
}
main() {
char name[20];
int age, choice = 1;
struct node *ptr;
while(choice != 3){
system("cls");
printf("1. Add a name\n");
printf("2. List nodes\n");
printf("3. Exit");
printf("\nEnter Menu Selection: ");
scanf("%d", &choice);
switch(choice) {
case 1: printf("\nEnter a name: ");
scanf("%s", name);
printf("Enter age: ");
scanf("%d", &age);
ptr = initnode(name, age);
break;
case 2: if(ptr == NULL) {
printf("Name %s not found\n", name);
} else
printnode(ptr);
pause;
break;
case 3: exit(3);
default: printf("Invalid Entry");
}// end of switch
}// end of main
}
哦,我知道有些“#include”可能没用。我整天都在添加和删除代码。
【问题讨论】:
-
看起来您甚至都没有在构建链接列表。例如,
head和end从不被引用。 -
哦,你不需要在 C 程序中强制转换
malloc的返回值。除此之外,NULL的所有演员都是怎么回事? -
您的转换是正确的,您不需要显式转换,在 C 编程中,完整它可能有时会导致错误...但这也是 不是你的答案
-
这句话真的有意义吗?
case 2: if(ptr == NULL) { printf("Name %s not found\n", name); } -
@EAGER_STUDENT,这取决于
printf的实现。在这种情况下,我的这里打印(null)。
标签: c pointers linked-list printf