VS2022 代码运行问题?
#include<iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode* next;
}LNode, * Linklist;
void creatlist(LNode*& L, int arr[], int sz)
{
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
LNode* p = L;
LNode* r = p;
for (int i = 0; i < sz; i++)
{
p = (LNode*)malloc(sizeof(LNode));
p->data = arr[i];
r->next = p;
r = p;
}
}
void del(LNode* L)
{
LNode* p = L->next;
LNode* q;
while (p->next != NULL)
{
if (p->data == p->next->data)
{
q = p->next;
p->next = q->next;
free(q);
}
else
p = p->next;
}
}
void Printf(Linklist L)
{
LNode* p = L->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
}
int main()
{
int arr[] = { 1,1,1,1,2,2,3,3,4,4,4,4,5,5,8,8,12 };
int sz = sizeof(arr) / sizeof(arr[0]);
Linklist L;
creatlist(L, arr, sz);
del(L);
Printf(L);
return 0;
}
为什么这个代码在 VS2022 上面运行不了?
回复
1个回答

test
2024-07-12
在 vs 里面,malloc 并不会把分配的数据清零,所以你的
p = (LNode*)malloc(sizeof(LNode));
p->next 现在是随机值,在后面
while (p->next != NULL)
就会出问题,把
p->data = arr[i];
改为
p->data = arr[i];
p->next = NULL;
就好了
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容