c/c++中使用结构体变量报错使用了未初始化变量L或者vs code运行可执行文件没有像预想的输出到终端
一个c/c++小问题
起先我的代码是这样的:
#include"list.h"
#include<stdio.h>
int main()
{
List *L;
ElemType x=10;
InitList(L,x);
printf("%%d
",L->first->next->data);
printf("%%d
",L->last->next->data);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
然后就报错如标题,后来发现是没有给list这个结构体申请内存空间的缘故,因此修改代码如下:
#include"list.h"
#include<stdio.h>
int main()
{
List *L= (List*)malloc(sizeof(List));
//或者使用这个语句
//List L=new List;
ElemType x=10;
InitList(L,x);
printf("%%d
",L->first->next->data);
printf("%%d
",L->last->next->data);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
推荐阅读