鱼C论坛

 找回密码
 立即注册
查看: 2569|回复: 2

输出为什么会溢出

[复制链接]
发表于 2019-1-5 09:18:48 | 显示全部楼层 |阅读模式
4鱼币

<div class="blockcode"><blockquote>#include <iostream>
using namespace std;

struct node
{
        int num;
        struct node *next;
};

node* createList();
void traverseList(node*);

int main()
{
        node *p = createList();
        traverseList(p);
        system("pause");
        return 0;
}

node* createList()
{
        node *head = new node;
        head->next = NULL;
        node *ptr = head;
        int a;
        cin >> a;
        while (0 != a)
        {
                node *s = new node;
                s->next = NULL;                               
                s->num = a;                       

                s->next = ptr->next;                                       
                ptr->next = s;

                cin >> a;
        }


        return head;
}

void traverseList(node *l)
{
        node* ptr = l;
        while (NULL != ptr)
        {
                cout << ptr->num << endl;
                ptr = ptr->next;
        }
}</blockquote></div><br />

链表.jpg
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-1-5 22:21:06 | 显示全部楼层
之所以输出这个感觉莫名其妙的数字,是因为在
node* createList();
这个函数体里:
node *head = new node;
初始化时已经new出对象,因为有了对象,所以这时head这个对象里的对应的结构
struct node
{
        int num;
        struct node *next;
};
中的成员变量
int num;
这里的对象head里的成员num已经有了一个值。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-1-5 23:51:34 | 显示全部楼层
修改后代码:
#include <iostream>
using namespace std;

struct node
{
        int num;
        struct node *next;
};

node* createList();
void traverseList(node*);

int main()
{
        node *p = createList();
        traverseList(p);
        system("pause");
        return 0;
}

node* createList()
{
        node *head = new node;
        head->next = NULL;
        head->num = NULL;
        node *ptr = head;
        int a;
        cin >> a;
        while (0 != a)
        {
                node *s = new node;
                s->next = NULL;                                
                s->num = a;                        
               
                s->next = ptr->next;                                       
                ptr->next = s;
               
                cin >> a;
        }
       
       
        return head;
}

void traverseList(node *l)
{
        node* ptr = l;
        while (NULL != ptr)
        {
                cout << ptr->num << endl;
                ptr = ptr->next;
        }
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-3 04:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表