首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

创建链表后将链表输出的有关问题

2012-10-16 
创建链表后将链表输出的问题C/C++ codestruct student{int nNumberint nSorcechar sName[20]struct stu

创建链表后将链表输出的问题

C/C++ code
struct student{    int nNumber;    int nSorce;    char sName[20];    struct student * spNext;};#define LEN sizeof(struct student)struct student * STD_creatLinkList(){    struct student * spHead;    struct student * sp1;    struct student * sp2;    int nIndex = 0;    int nFlag = 0;    sp1 = (struct student *) malloc(LEN);    sp2 = (struct student *) malloc(LEN);    spHead = sp1;    for (nIndex = 0; nIndex < 5; nIndex++)    {            sp1->nNumber = 1201 + nIndex;        sp1->nSorce = 0;        strcpy(sp1->sName, "student");        sp1->spNext = sp2;        sp1 = sp2;            sp2 = (struct student *) malloc(LEN);            }    sp1->spNext = NULL;    return spHead;}void main(){    struct student * spHead;    spHead = STD_creatLinkList();    while(spHead != NULL)    {        printf("%d,%d,%s\n",spHead -> nNumber,spHead -> nSorce,spHead -> sName);        spHead = spHead -> spNext;    }    while(1)    {    }}



这样为什么会输出五个值?

[解决办法]
sp1 = sp2;
sp2 = (struct student *) malloc(LEN);
每次往后移一个,然后重新赋值,为啥不是5个,实际上运行输出6个,最后一个是乱码,未初始化的
[解决办法]
虽然lz达到目的,了但是这段代码,问题很多。

不该申请空间的时候没必要申请空间,只需要两个指针就行了,每次申请一次就够。

热点排行
Bad Request.