2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > c语言+结构体指针初始化 c语言结构体指针初始化===

c语言+结构体指针初始化 c语言结构体指针初始化===

时间:2022-06-08 22:36:12

相关推荐

c语言+结构体指针初始化 c语言结构体指针初始化===

c语言结构体指针初始化 今天来讨论一下C中的内存管理。

记得上周在饭桌上和同事讨论C语言的崛起时,讲到了内存管理方面

我说所有指针使用前都必须初始化,结构体中的成员指针也是一样

有人反驳说,不是吧,以前做二叉树算法时,他的左右孩子指针使用时难道有初始化吗

那时我不知怎么的想不出理由,虽然我还是坚信要初始化的

过了几天这位同事说他试了一下,结构体中的成员指针不经过初始化是可以用(左子树和右子树指针)

那时在忙着整理文档,没在意

今天抽空调了一下,结论是,还是需要初始化的。

而且,不写代码你是不知道原因的(也许是对着电脑久了IQ和记性严重下跌吧)

测试代码如下

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.

19.

20.

21.

22.

23.

24.

25.

26. #include #include #include struct student{ char *name; int score; struct student* next; }stu,*stu1; int main(){ = (char*)malloc(sizeof(char)); /*1.结构体成员指针需要初始化*/ strcpy(,"Jimy"); stu.score = 99; stu1 = (struct student*)malloc(sizeof(struct student));/*2.结构体指针需要初始化*/ stu1->name = (char*)malloc(sizeof(char));/*3.结构体指针的成员指针同样需要初始化*/ stu.next = stu1; strcpy(stu1->name,"Lucy"); stu1->score = 98; stu1->next = NULL; printf("name %s, score %d \n ",, stu.score); printf("name %s, score %d \n ",stu1->name, stu1->score); free(stu1); return 0; }

#include

#include

#include

struct student{

char *name;

int score;

struct student* next;

}stu,*stu1;

int main(){

= (char*)malloc(sizeof(char)); /*1.结构体成员指针需要初始化*/

strcpy(,"Jimy");

stu.score = 99;

stu1 = (struct student*)malloc(sizeof(struct

student));/*2.结构体指针需要初始化*/

stu1->name =

(char*)malloc(sizeof(char));/*3.结构体指针的成员指针同样需要初始化*/

stu.next = stu1;

strcpy(stu1->name,"Lucy");

stu1->score = 98;

stu1->next = NULL;

printf("name %s, score %d \n ",, stu.score);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。