C語言——指標與結構體 記憶體的動態分配

來源:互聯網
上載者:User

例一 :

 1 #include <stdio.h>
2 #include <string.h>
3
4 struct Student {
5 int sid ;
6 char name[200] ;
7 int age ;
8 };
9
10 void f(struct Student *p);
11 void g(struct Student *p);
12 void h(struct Student stu);
13
14 int main()
15 {
16 struct Student stu ;
17
18 f(&stu);
19 g(&stu);
20 h(stu);
21
22 //printf("%d %s %d \n" ,stu.sid , stu.name , stu.age);
23
24 return 0 ;
25 }
26
27 void g(struct Student *p) //用指標可以減小記憶體佔用 , 節省時間提高效率
28 {
29 printf("%d %s %d \n", p -> sid , p -> name , p -> age);
30 }
31
32 void h(struct Student stu) //值傳遞
33 {
34 printf("%d %s %d \n", stu.sid , stu.name ,stu.age);
35 }
36
37 void f(struct Student *p) //輸入函數
38 {
39 (*p).sid = 23 ; //等價 p -> sid = 23 ;
40 strcpy( p -> name , "zhangsan");
41 p -> age = 34 ;
42 }

例二 :

 1 //////////////////////////////////
2 // ——注釋部分為第二種方法——///
3 //////////////////////////////////
4 #include <stdio.h>
5 #include <malloc.h>
6
7 struct Student
8 {
9 int sid ;
10 int age ;
11 };
12
13 //struct Student *CreateStudent(struct Student **q);
14 struct Student *CreateStudent(void);
15 void ShowStudent(struct Student *);
16
17 int main()
18 {
19 struct Student *p ;
20
21 //p = CreateStudent(&p);
22 p = CreateStudent();
23 ShowStudent(p);
24
25 return 0 ;
26 }
27
28 //struct Student *CreateStudent(struct Student **q)
29 struct Student *CreateStudent(void)
30 {
31 /*
32 *q = (struct Student *)malloc(sizeof(struct Student));
33
34 (*q) -> sid = 78 ; // " -> "優先順序大於" * "
35 (*q) -> age = 23 ;
36 return *q;
37 */
38 struct Student *p = (struct Student *)malloc(sizeof(struct Student));
39
40 p -> sid = 78 ;
41 p -> age = 23 ;
42
43 return p ;
44 }
45
46 void ShowStudent(struct Student *ps)
47 {
48 printf("%d %d \n" , ps -> sid , ps -> age);
49 }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.