结构体指针初始化问题

(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;


  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
结构体指针初始化可以使用memset函数来实现。memset函数是C语言中的一个库函数,用于将一块内存空间的值设置为指定的值。 在结构体指针初始化时,可以使用memset函数将结构体指针所指向的内存空间全部设置为0或其他指定的值。具体使用方法如下: 1. 首先,需要包含头文件string.h,该头文件中包含了memset函数的声明。 2. 然后,定义一个结构体类型,并声明一个结构体指针变量。 3. 使用malloc函数为结构体指针分配内存空间。 4. 最后,使用memset函数对结构体指针所指向的内存空间进行初始化。 下面是一个示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义一个结构体类型 typedef struct { int id; char name[20]; float score; } Student; int main() { // 声明一个结构体指针变量 Student *stuPtr; // 使用malloc函数为结构体指针分配内存空间 stuPtr = (Student *)malloc(sizeof(Student)); // 使用memset函数对结构体指针所指向的内存空间进行初始化 memset(stuPtr, 0, sizeof(Student)); // 输出初始化后的结果 printf("id: %d\n", stuPtr->id); printf("name: %s\n", stuPtr->name); printf("score: %.2f\n", stuPtr->score); // 释放内存空间 free(stuPtr); return 0; } ``` 上述代码中,使用memset函数将结构体指针stuPtr所指向的内存空间全部设置为0。输出结果为: ``` id: 0 name: score: 0.00 ``` 这样就完成了结构体指针初始化

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值