C语言 结构体

来源:互联网 发布:linux 显示 ping 来源 编辑:程序博客网 时间:2024/05/28 15:56

#include <stdio.h>

#include <stdlib.h>


struct Student{

    

   char name[100];

   int age;

   float score ;

};


typedef struct {


   char *name;      //字符指针

   int age;

   float score;

    

}NewStudent;


int main(int argc,const char * argv[]) {

   

   /*

     结构体:C语言提供开发者来自定义数据类型

     结构体的定义:

        struct 结构体名称(最好大写){

            

            类型  变量1;

            类型  变量2;

            ...

        };

     注意:结构体定义,在花括号后面加分号

     */

    

   /*

     结构体变量初始化  struct 结构体名 变量名 = {1,2,...};

     */

   struct Student st = {"Rick",25,99.9};

    

   NewStudent student = {"Rick",25,99.9};

    

    //取结构体元素用'.'

   printf("%s\n",st.name);

   printf("%d\n",st.age);

   printf("%f\n",st.score);

    

    //求结构体占内存字节数

    

    int length = sizeof(char)*100 +sizeof(int) +sizeof(float);

    printf("length = %d\n",length);

    

    //用户自己开辟内存 使用malloc函数, #include<stdlib.h>

   char *theName = (char *)malloc(sizeof(char)*100);

   char *tmp = "张三";

    theName = tmp;

    student.name = theName;

   printf("%s\n",student.name);

    


   return 0;

}


0 0