C语言问题,为什么输出总是乱码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#define N sizeof(struct equ)
struct equ
{
char num[10];
char name[20];
char model[20];
char price[10];
char date[20];
char user[20];
char remark[50];
struct equ *next;
};
struct equ *input()
{
struct equ *head;
struct equ *p1,*p2;
int n=0;
p1=p2=(struct equ *)malloc(N);
printf("Please input 'number name model price date user remark\n");
while(1)
{
n=n+1;
if ( n==1 )
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct equ *)malloc(N);
printf("Number: ");gets(p1->num);fflush(stdin);
printf("Name: ");gets(p1->name);fflush(stdin);
printf("Model: ");gets(p1->model);fflush(stdin);
printf("Price: ");gets(p1->price);fflush(stdin);
printf("Date: ");gets(p1->date);fflush(stdin);
printf("user: ");gets(p1->user);fflush(stdin);
printf("Remark: ");gets(p1->remark);fflush(stdin);
printf("end?y or n");if(getch()=='y'){clrscr();break;}
clrscr();
}
p2->next=NULL;
printf("The end\n");
return(head);
}
struct equ *output(struct equ *h)
{
struct equ *p;
p=h;
clrscr();
if(h!=NULL)
do
{puts(p->num);
puts(p->name);
puts(p->remark);
printf("\n\n");
p=p->next;
}while(p!=NULL);
return(h);
}
main()
{
struct equ *h=NULL;
h=input();
output(h);
getch();
}

第1个回答  2014-12-29
看一眼就知道。。乱码是因为你的指针没有赋NULL,是野指针,指向了不明区域,所以会出现乱码,以后定义指针最好int *a = NULL;这样子
第2个回答  2014-12-29
struct equ *input()
{
 struct equ *head;
 struct equ *p1,*p2;
 int n=0;
 //p1=p2=(struct equ *)malloc(N);
 printf("Please input 'number name model price date user remark\n");
 while(1)
 {
   p1=(struct equ *)malloc(N);//here
     n=n+1;
   if ( n==1 )
     head=p1;
   else
     p2->next=p1;
   p2=p1;
   printf("Number: ");gets(p1->num);fflush(stdin);
   printf("Name:   ");gets(p1->name);fflush(stdin);
   printf("Model:  ");gets(p1->model);fflush(stdin);
   printf("Price:  ");gets(p1->price);fflush(stdin);
   printf("Date:   ");gets(p1->date);fflush(stdin);
   printf("user:   ");gets(p1->user);fflush(stdin);
   printf("Remark: ");gets(p1->remark);fflush(stdin);
   printf("end?y or n");if(getch()=='y'){clrscr();break;}
   clrscr();
 }
 p2->next=NULL;
 printf("The end\n");
 return(head);
}

head那里,多申请了一块内存,导致head指向的空间没有被赋值过,也没有初始化,输出会是乱码。

本回答被提问者采纳
第3个回答  2014-12-29
input中的链表算法有问题
最后返回的head不是期望的头结点