qq_41034308 2021-01-16 16:57 采纳率: 50%
浏览 113
已采纳

同一份代码在vs2019上不能正常运行,在牛客网的c++(clang++11)上面可以正常运行

#include<iostream>
using namespace std;
struct node
{
	int num;
	node* l;
	node* r;
};
void built(node*& root, int num)
{
	if (root == NULL)
	{
		root = (node*)malloc(sizeof(node));
		if (root)
			root->num = num;
		return;
	}
	if (root->num == num)
		return;
	if (root->num > num)
		built(root->l, num);
	else
		built(root->r, num);
}
void NLR(node* root)
{
	if (root == NULL)
		return;
	cout << root->num << " ";
	NLR(root->l);
	NLR(root->r);

}
void LNR(node* root)
{
	if (root == NULL)
		return;
	LNR(root->l);
	cout << root->num << " ";
	LNR(root->r);
}
void LRN(node* root)
{
	if (root == NULL)
		return;
	LRN(root->l);
	LRN(root->r);
	cout << root->num << " ";
}
int main()
{
	int length, a;
	node* root;
	while (cin >> length)
	{
		root = NULL;
		for (size_t i = 0; i < length; i++)
		{
			cin >> a;
			built(root, a);
		}
		NLR(root);
		cout << endl;
		LNR(root);
		cout << endl;
		LRN(root);
		cout << endl;
	}
}

不是第一次了,如果使用指针的话,vs2019很可能会出错。

上图是vs2019的结果。

http:/t.cn/AiKD0L5V这个链接是这道编程题。

  • 写回答

1条回答 默认 最新

  • include_iostream_ 2021-01-16 19:37
    关注

    这种玄学问题里边,十个有八个与缺少完善的初始化有关,试试在分配结点后立即将结点的l和r置为nullptr。(一个常见的误解是“malloc可以自动清零”,这个想法其实是错误的。)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!