如题
#include<iostream>
#include<stdlib.h>
using namespace std;
struct test //定义结构体 test
{
int temp1; //元素不赋默认值
int temp2=99;//元素赋默认值
};
int main()
{
test a; //直接声明结构体a
cout<<"直接声明结构体a对赋初始值的影响"<<endl;
cout<<a.temp1<<" "<<a.temp2<<endl;
test* b=(test*)malloc(sizeof(test)); //通过malloc分配空间建立结构体b
cout<<"过malloc分配空间建立结构体b对赋初始值的影响"<<endl;
cout<<b->temp1<<" "<<b->temp2<<endl;
}
输出结果:
结论:通过malloc分配空间建立结构体变量不会对结构体中的元素赋初始值,为随机值,malloc只分配了空间。