该程序不打印任何内容。我不明白它的行为。 [英] This program doesn't print anything. I don't understand it's behaviour.

查看:75
本文介绍了该程序不打印任何内容。我不明白它的行为。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include    <   stdio.h  >  
#include < conio .h >
#include < alloc.h > ;
struct 已链接
{ int 数据;
struct linked * next;
};
void insert( struct linked * root, int ele);

void main()
{
struct linked * root = NULL;
struct linked * temp;
insert(root, 4 );
insert(root, 6 );
insert(root, 7 );
insert(root, 1 );
insert(root, 3 );
insert(root, 9 );
temp = root;
while (temp!= NULL)
{
printf( %d \ n,temp-> data);
temp = temp-> next;
}
}


void insert( struct 链接* root, int ele)
{
struct 已链接* newnode =( struct linked *)malloc( sizeof struct linked));
newnode-> data = ele;
newnode-> next = root;
root = newnode;
}

解决方案

该程序表现得像预期的那样。

  void  insert( struct  linked * root, int  ele); 



永远不会改变root。



问题是在你的声明中插入到链表中,你传递的是指针的值,而不是指针的地址。这意味着指针的副本被传递到堆栈而不是指针的地址。



将函数声明为:

< pre lang =c ++> void insert( struct linked ** root, int ele);





然后电话将采用以下形式:

 insert(& root, 6 ); 





如果需要,请尝试并寻求更多帮助。





你需要在脑海中清醒关于指针本身与它指向的内容之间的区别。

在C ++中,您可以使用引用并通过声明修复程序:

  void  insert( struct  linked *& root, int  ele); 





见这里(参考文献1总结它up):

http://www.eskimo.com/~scs /cclass/int/sx8.html [ ^ ]



指针指针和指针引用 [ ^ ]



因为SA说调试器是你的朋友有这种问题


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct linked
{int data;
struct linked *next;
};
void insert(struct linked *root,int ele);

void main()
{
struct linked *root=NULL;
struct linked *temp;
insert(root,4);
insert(root,6);
insert(root,7);
insert(root,1);
insert(root,3);
insert(root,9);
temp=root;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}


void insert(struct linked *root,int ele)
{
struct linked *newnode=(struct linked *)malloc(sizeof(struct linked));
newnode->data=ele;
newnode->next=root;
root=newnode;
}

解决方案

The program is behaving as one would expect.

void insert(struct linked *root,int ele);


never changes root.

The problem is that in your declaration for an insert into the linked list you are passing the value of a pointer and not the address of the pointer. This means a copy of the pointer is passed onto the stack instead of the address of the pointer.

Declare the function as:

void insert(struct linked **root,int ele);



Then calls will be of the form:

insert(&root,6);



Try that and ask for more help if required.

[EDIT]
You need to be clear in your mind about the difference between the pointer itself and what it points to.
In C++ you could have used a reference and fixed the program by declaring:

void insert(struct linked *&root,int ele);



See here (Reference 1 sums it up):
http://www.eskimo.com/~scs/cclass/int/sx8.html[^]

Pointer to Pointer and Reference to Pointer[^]

As SA has said the debugger is your friend with this type of problem.


这篇关于该程序不打印任何内容。我不明白它的行为。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆