#include
#include
#include
//声明结构体
struct Student //student结构体名
{
char name[32]; //不要写成 char name[32] = {0};
int age;
char sex;
};
int main()
{
struct Student s1; //定义结构体变量
struct Student s2 = {"aaaaa", 20, 'm'}; //初始化结构体变量
//s1.name = "bbbb";
strcpy(s1.name, "bbbb");
s1.age = 22;
s1.sex = 'm';
//打印结构体变量,逐个打印
printf("%s %d %c\n", s1.name, s1.age, s1.sex); //通过结构体变量访问结构体成员,用符号 .
printf("%s %d %c\n", s2.name, s2.age, s2.sex); //通过结构体变量访问结构体成员,用符号 .
struct Student *s3; //结构体指针
s3 = (struct Student *)malloc(sizeof(struct Student));
strcpy(s3->name, "cccc");
s3->age = 24;
s3->sex = 'm';
printf("%s %d %c\n", s3->name, s3->age, s3->sex);
scanf("%s", s1.name); //不需要取地址
scanf("%s", s3->name);
scanf("%d", &s3->age);
free(s3);
return 0;
}
注:
char *ptr;
ptr = "helloworld";
/*******
char str[32];
str = "helloworld"; //str是常指针,不能被赋值,数组与字符串不能直接赋值,可以通过拷贝或单个元素赋值。
*******/错误的
#include
#include
#include
int global = 0;
char *p1;
int main()
{
int a;
char s[] = "abcd";
char *p2;
char *p3 = "123456789";
static int c = 0;
printf("%p\n", p3);
printf("%p\n", &p1);
printf("%p\n", &c);
printf("%p\n", &a);
printf("%p\n", s);
p1 = (char *)malloc(100);
printf("%p\n", p1);
strcpy(p1, "123456789");
return 0;
}
注:
堆和栈区别:
栈:操作系统管理
堆:用户管理
(1).
struct Test
{
int a;
int b;
};
typedef struct Test T;
(2).
typedef struct Test
{
int a;
int b;
} T ;
(1).结构体总长度一定是最长成员的整数倍(double除外);
(2).每个成员的偏移量一定是该成员长度的整数倍。
#include
//1、结构体总长度一定是最长成员的整数倍
//2、每个成员的偏移量一定是该成员长度的整数倍
struct Test
{
int a;
char b;
};
typedef struct Test T;
struct Test2
{
short a;
T t1;
char c;
};
int main()
{
int a = 1;
printf("%p\n", &a);
printf("%d\n", sizeof(T));
printf("%d\n", sizeof(struct Test2));
return 0;
}
#include
struct Student
{
char name[32];
int age;
};
typedef struct Student stu;
int main()
{
stu s[10]; //结构体数组
int i;
for (i = 0; i < 3; i++)
{
scanf("%s%d", s[i].name, &s[i].age);
}
for (i = 0; i < 3; i++)
{
printf("%s %d\n", s[i].name, s[i].age);
}
stu *s1[10]; //结构体指针数组
for (i = 0; i < 3; i++)
{
s[i] = (stu *)malloc(sizeof(stu));
scanf("%s%d", s[i]->name, &s[i].age);
}
return 0;
}
#include
//联合体特点:所有成员共享同一段内存空间 联合体长度:最长成员的长度
union test
{
int a;
int b;
char c;
};
int main()
{
union test t;
printf("%d\n", sizeof(t));
t.a = 100;
printf("%d\n", t.b);
return 0;
}
#include
union test
{
short val;
char ch[sizeof(short)];
};
int main()
{
union test t;
t.val = 0x0102;
if (t.ch[0] == 1 && t.ch[1] == 2)
{
printf("大端字节序\n");
}
else if (t.ch[0] == 2 && t.ch[1] == 1)
{
printf("小端字节序\n");
}
return 0;
}
#include
int main()
{
int a = 1;
printf("%d\n", ((a & 0x000000ff) << 24) |
((a & 0x0000ff00) << 8) |
((a & 0x00ff0000) >> 8) |
(a & 0xff000000) >> 24);
return 0;
}
#include
/*
#define SUN 0
#define MON 1
#define TUE 2
#define WEN 3
*/
enum{
SUN = 10,
MON,
TUE = 100,
WEN
}; //属于常量
int main()
{
printf("%d\n", SUN);
printf("%d\n", MON);
printf("%d\n", TUE);
printf("%d\n", WEN);
return 0;
}
system("clear"); //清屏
exit(0); //退出进程
free(s3); //释放申请的内存空间