结构体指针初始化问题
2017-08-22 20:02
465 查看
(1)结构体指针是否需要初始化
struct student{
char* name;
int score;
struct student* next;
}stu,*stu1;
stu.name=(char*)malloc(sizeof(char)); //1 结构体成员指针需要初始化
strcpy(stu.name,"Jim");
stu.scor=90;
stu1=(struct student*)malloc(sizeof(struct student)); //2 结构体指针需要初始化
sut1->name=(char*)malloc(sizeof(char)); //3 结构体指针的成员指针同样需要初始化
stu->next=stu1;
strcpy(stu1->name,"Lucy");
stu1->score=80;
stu1->next=NULL;
数据结构中二叉树遍历算法中所用的左子树,右子树看似不用初始化,其实是因为子树必须是二叉节点类型的结构体指针,而该结构体指针是需要初始化的,没有通过malloc来分配,而是将另一个指针的指赋给它。
struct node
{
int data;
struct node* lchild,rchild;
};
struct node* root;
root=(struct node*)malloc(sizeof(struct node));
root-data=3;
struct node* nlchild;
nlchild=(struct node*)malloc(sizeof(strucut node));
root->lchild=nlchild;
nlchild->data=2;
nlchild->lchild=nlchild->rchild=NULL;
struct node* nrchild;
nrchild=(struct node*)malloc(sizeof(struct node));
root->rchild=nrchild;
nrchild->data=4;
nrchild->lchild=nrchild->rchild=NULL;
struct student{
char* name;
int score;
struct student* next;
}stu,*stu1;
stu.name=(char*)malloc(sizeof(char)); //1 结构体成员指针需要初始化
strcpy(stu.name,"Jim");
stu.scor=90;
stu1=(struct student*)malloc(sizeof(struct student)); //2 结构体指针需要初始化
sut1->name=(char*)malloc(sizeof(char)); //3 结构体指针的成员指针同样需要初始化
stu->next=stu1;
strcpy(stu1->name,"Lucy");
stu1->score=80;
stu1->next=NULL;
数据结构中二叉树遍历算法中所用的左子树,右子树看似不用初始化,其实是因为子树必须是二叉节点类型的结构体指针,而该结构体指针是需要初始化的,没有通过malloc来分配,而是将另一个指针的指赋给它。
struct node
{
int data;
struct node* lchild,rchild;
};
struct node* root;
root=(struct node*)malloc(sizeof(struct node));
root-data=3;
struct node* nlchild;
nlchild=(struct node*)malloc(sizeof(strucut node));
root->lchild=nlchild;
nlchild->data=2;
nlchild->lchild=nlchild->rchild=NULL;
struct node* nrchild;
nrchild=(struct node*)malloc(sizeof(struct node));
root->rchild=nrchild;
nrchild->data=4;
nrchild->lchild=nrchild->rchild=NULL;
相关文章推荐
- 指针未初始化引发的程序奔溃问题
- 问题:指针为什么使用前要进行初始化及相关例子
- 【java基础】引用类型数组初始化中,setter和getter函数空指针问题
- [置顶] 记录一个指针问题(内存空间的初始化)
- 有关结构体中的指针问题
- 指针不初始化就传递的问题
- 关于声明指针初始化问题
- (原)C++中指针不初始化就传递的问题
- 结构体对齐导致结构体数组大小变化引发的指针越界操作问题.
- 结构体数组的指针初始化与内存释放
- 关于为结构体指针申请内存的问题
- C中struct(结构体)初始化的问题
- C语言结构体初始化出现 too many initializer values 问题
- 指针与引用的初始化&顶层底层const变量初始化问题
- 结构体定义使用及指针长度问题
- C语言定义了一个结构体怎么分配内存?C\C++中结构体变量与结构体指针内存分配问题?
- C语言定义了一个结构体怎么分配内存?C\C++中结构体变量与结构体指针内存分配问题?
- struct 结构体的定义及初始化问题
- 【转载】c语言结构体指针初始化
- 指向结构体的指针必须初始化