加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

struct几种定义的方法

发布时间:2020-12-15 01:01:33 所属栏目:百科 来源:网络整理
导读:#include stdio.h /** 一般定义形式 */ ? ? struct student{ ? ? char *name; ? ? int age; ? ? double score; } define1(){ ? ? struct student stu; ? ? stu.name="hello"; ? ? stu.age=20; ? ? printf("student name%sn",stu.name); ? //hello ? ? print
#include <stdio.h> /** 一般定义形式 */ ? ? struct student{ ? ? char *name; ? ? int age; ? ? double score; } define1(){ ? ? struct student stu; ? ? stu.name="hello"; ? ? stu.age=20; ? ? printf("student name%sn",stu.name); ? //hello ? ? printf("student age %dn",stu.age); //20 } /** ? ? 在定义时给出结构变量名 */ struct people{ ? ? ?char *username; ? ? ?int age; }body; define2(){ ? ? ?body.username="flex"; ? ? ?body.age="nihao"; ? ? ?printf("people.name %sn",body.username);//flex ? ? ?printf("people.age %sn",body.age); ? ? //age; } /** ? ? 匿名结构,光给出结构变量名,没有给定结构名 */ struct { ? ? int age; }teacher,stu; define3(){ ? ? teacher.age=20; ? ? stu.age=30; ? ? printf("teacher.age %d n stu.age %d n",teacher.age,stu.age); //20 30 } /** ?使用宏定义 */ #define UT struct cat UT{ ? ? ?char * carName; } define4(){ ? ? UT a; ? ? //cat st; ? ?//不可以这样定义 ? ? //ct.carName="my first cat"; ? ? a.carName="my cat"; ? ?// printf("my first car%sn",ct.carName); ? ? printf("my cat%s ?",a.carName);// my cat ? ?? } struct initMember{ ? ? int st; ? ? int h; }member={2,3},member1; initDefine(){ ? ? printf("nmember init %d,",member.st);//2 ? ? member1=member; ? ? printf("member1.st %dn + member1.h %dn",member1.st,member1.h);//2,3 } struct sarray{ ? ? int a,b; }str[3],sarr[2]={ ? ? ? ? {1,2},? ? ? ? {3,8},? ? ? ? }; structArray(){ ? ? struct sarray sp[2]; ? ? int i; ? ? sp[0].a=1; ? ? sp[1].a=2; ? ? sp[0].b=0; ? ? sp[1].b=4; ? ? for(i=0;i<2;i++){ ? ? ? ? printf("sp %d 的a %dn",i,sp[i].a); ? //8 ? ? } ? ?? ? ? str[0].a=5; ? ? printf("array[0].a=%d",str[0].a);//5 ? ?? ? ? printf("nsarr[1].b=%dn",sarr[1].b); } struct structPoint{ ? ? char c; }sp={'a'}; structPoint(){ ? ? /* 其访问的一般形式为: ? ? (*结构指针变量).成员名 ? ?或为: ? ? ? ? 结构指针变量->成员名*/ ? ? struct structPoint *p=&sp; ? ? printf("结构指针的指向的值是%cn",(*p).c); ? ? printf("结构指针访问值的第2种方式%cn",p->c); } //typedef 是给类型起别名,那么还可以给struct起别名 typedef int Integer; typedefsample(){ ? ? Integer a=2; ? ? printf("typdef int a=%d",a); } //typedef一个结构 typedef struct TestTypeDefStruct{ ? ? char *p; } DEFSTRUCT; typedefStruct(){ ? ? DEFSTRUCT ttds; ? ? ttds.p="typedef define a struct"; ? ? printf("typedef 定义一个结构%sn",ttds.p); } //typedef demo De; /* demo2(){ ? ? De sp; ? ? sp.a=2; }*/ int main(int args,char* arg0){ ? ? ?//定义的4种方式 ? ? ?define1(); ? ? ?define2(); ? ? ?define3(); ? ? ?define4(); ? ? ?initDefine();//结构变量的初始化 ? ? ?structArray();//结构数组的定义 ? ? ?structPoint();//指向结构变量的指针,struct 结构名 *结构指针变量名 ? ? ?typedefsample();//typedef定义一个整形 ? ? ?typedefStruct(); ? ? // demo(); }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读