结构体全局变量,局部变量
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
struct Stu {
char name[20];
char tele[12];
char sex[10];
int age;
}s4, s5, s6;
struct Stu s3;
int main() {
struct Stu s1;
struct Stu s2;
return 0;
}
结构体嵌套初始化
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
struct T
{
double weight;
short age;
};
struct S {
char c;
struct T st;
int a;
double d;
char arr[20];
};
int main() {
struct S s = { 'c',{55.6,30},100,3.14,"hello world" };
printf("%c %d %lf %s\n", s.c, s.a, s.d, s.arr);
printf("%lf %d\n", s.st.weight,s.st.age);
return 0;
}
c 100 3.140000 hello world
55.600000 30
结构体内存对齐
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
struct S1 {
char c1;
char c2;
int a;
};
struct S2 {
char c1;
int a;
char c2;
};
struct S3 {
double d;
char c;
int a;
};
struct S4 {
char c1;
struct S3 s3;
double d;
};
int main() {
struct S1 s1 = { 0 };
printf("%d\n", sizeof(s1));
struct S2 s2 = { 0 };
printf("%d\n", sizeof(s2));
struct S3 s3 = { 0 };
printf("%d\n", sizeof(s3));
struct S4 s4 = { 0 };
printf("%d\n", sizeof(s4));
}
8
12
16
32
结构体传参
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
struct S {
int a;
char c;
double d;
};
void Init(struct S* ps) {
ps->a = 100;
ps->c = 'w';
ps->d = 3.14;
}
void Print1(struct S tmp) {
printf("%d %c %lf\n", tmp.a, tmp.c, tmp.d);
}
void Print2(struct S* ps) {
printf("%d %c %lf\n", ps->a, ps->c, ps->d);
}
int main() {
struct S s = { 0 };
Init(&s);
Print1(s);
Print2(&s);
}
100 w 3.140000
100 w 3.140000
|