c语言程序输出的数据后面多了一些乱码

程序如下:作用是建立链表并输出,学生的信息包括号码,姓名,籍贯。
在输入如: input records:
100,xiao,guangzhou(回车)
101,ming,shanghai(回车)
0,0,0(回车)
输出结果:Now,these 2 records are:
100,xiao,guangzhou(后面有乱码)
101,ming,shanghai(后面有乱码)
问题:怎么去掉那些乱码?
#include<stdio.h>
#include<malloc.h>
#define NULL 0
#define LEN sizeof(struct student)

struct student
{long num;
char name[15];
char bthplc[15];
struct student * next;
};

int n;

struct student * creat(void)
{struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *)malloc(LEN);
scanf("%ld,%s,%s",&p1->num,p1->name,p1->bthplc);
head=NULL;
while(p1->num!=0)
{n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%ld,%s,%s",&p1->num,p1->name,p1->bthplc);
}
p2->next=NULL;
return(head);
}

void print(struct student *head)
{struct student *p;
printf("\nNow,these %d records are:\n",n);
p=head;
if(head!=NULL)
do
{printf("%ld,%s,%s\n",p->num,p->name,p->bthplc);
p=p->next;
}while(p!=NULL);
}

void main()
{struct student *head,stu;
printf("input records:\n");
head=creat();
print(head);
}
如果是数组越界那要怎么解决?

这个不是数组越界的问题。
scanf()对字符串的输入是不可以用逗号做间隔的。对于:
scanf("%ld,%s,%s",&p1->num,p1->name,p1->bthplc);
如果你输入的是:
100,xiao,guangzhou
那么执行后的结果是:
p1->num:100
p1->name:xiao,guangzhou
p1->bthplc:(未初始化,数据不可知)
由于p1->bthplc未初始化,所以会有乱码出现。
建议你采用三个数据分开输入的方式解决这个问题。如:
scanf("%ld,%s",&p1->num,p1->name);
scanf("%s",p1->bthplc);
输入时在name后面换行,这样:
100,xiao(回车)
guangzhou(回车)
101,ming(回车)
shanghai(回车)
0,0(回车)
0(回车)
这只是个折中的办法,不是很好,希望你可以写一个以逗号分割字符串的子函数实现愿意。
数组越界可以通过加大数组长度,或者动态开辟内存的方法解决。
另外,建议你把malloc开辟的内存在最后释放掉,养成个好习惯。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-06-07
一般出现这种情况是数组越界了
相似回答