#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
struct Bok//定义结构体的同时给结构体赋值
{
char title[50];
char author[50];
char subject[100];
int book_id;
} bok = {"C 语言", "RUNOOB", "编程语言", 123456};
struct yan
{
char a[50];
char b[50];
char c[100];
int d;
};
//用typedef创建新类型
typedef struct
{
int a;
char b;
double c;
} Simple2;
//现在可以用Simple2作为类型声明新的结构体变量
void printyan( struct yan *book )
{
printf( "--通过结构体指针访问成员变量--\n");
printf( "a : %s\n", book->a);
printf( "b : %s\n", book->b);
printf( "c : %s\n", book->c);
printf( "d : %d\n", book->d);
printf( "-----------------------\n");
printf( "-----------------------\n");
}
/* 函数声明 */
void printBook( struct Books *book );
int main( )
{
struct Books Book1; /* 声明 Book1,类型为 Books */
struct Books Book2; /* 声明 Book2,类型为 Books */
struct yan yan1;
struct yan *y;//定义一个结构体类型指针
Simple2 u1;
u1.a=1;
u1.b=2;
u1.c=1.1;
printf( "u1.a :%d\n", u1.a);
printf( "u1.b :%d\n", u1.b);
printf( "u1.c :%f\n", u1.c);
printf( "---------------------------------------------------------------------\n");
printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", bok.title, bok.author, bok.subject, bok.book_id);
printf( "---------------------------------------------------------------------\n");
strcpy( yan1.a, "abc");
yan1.a[3]=0x31;
yan1.a[4]=0x32;
yan1.a[5]=0x32;
printf( "yan :0x %x\n", yan1.a[5]);//直接访问成员变量
strcpy( yan1.b, "ABC");
strcpy( yan1.c, "ABc123");
yan1.d = 21;
printyan(&yan1);
y=&yan1;//指针变量赋值
printyan(y);
/* Book1 详述 */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* Book2 详述 */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* 通过传 Book1 的地址来输出 Book1 信息 */
printBook( &Book1 );
/* 通过传 Book2 的地址来输出 Book2 信息 */
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
C 数组允许定义可存储相同类型数据项的变量,结构是 C 编程中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。
在C语言中,可以使用结构体(Struct)来存放一组不同类型的数据。结构体的定义形式为:
struct 结构体名{
结构体所包含的变量或数组
};
你也可以在定义结构体的同时定义结构体变量:
struct stu{
char *name; //姓名
int num; //学号
int age; //年龄
char group; //所在学习小组
float score; //成绩
} stu1, stu2;
将变量放在结构体定义的最后即可。
如果只需要 stu1、stu2 两个变量,后面不需要再使用结构体名定义其他变量,那么在定义时也可以不给出结构体名,如下所示:
struct{ //没有写 stu
char *name; //姓名
int num; //学号
int age; //年龄
char group; //所在学习小组
float score; //成绩
} stu1, stu2;
这样做书写简单,但是因为没有结构体名,后面就没法用该结构体定义新的变量。
结构体中 . 和 ->的区别
区别:
->:用在结构体指针的时候
. :用在结构体后面(".“这个运算符可以理解为中文里"的”)
. 翻译成中文 “的”
-> 结构体指针中使用
–>的左边应该是个指向结构体的指针,右边是结构体的元素
注意定义完指针要malloc空间赋给指针,不然指针指向空域,自然出错
. 的左边应该是个结构体本身,用. 能表示他的元素