联合
#include <stdio.h>
union hold{
int digit;
double big;
char letter;
};
struct cat {
char miao[10];
};
struct dog {
char wang[10];
};
union data {
struct cat my_cat;
struct dog my_dog;
};
// 联合的用法:将多个类型放在同一个结构中,使用状态区别
struct my_pet
{
int status; // 0:cat , 1:dog
union data pet;
};
int main(int argc, char *argv[])
{
// 联合只存储一个值
union hold valA;
valA.letter = 'A';
union hold valB = valA;
union hold valC = { 88 }; // 初始化digit成员
union hold valD = { .big = 10.00 }; //指定初始化成员
// 联合与结构的访问方式相同
return 0;
}
枚举
#include <stdio.h>
enum color { red, yellow = 10, green, blue };
int main(int argc, char *argv[])
{
printf("red: %d ,yellow: %d ,green: %d ,
", red, yellow, green);
int c = 11;
switch (c)
{
case red: puts("oh red.
"); break;
case yellow: puts("oh yellow.
"); break;
case green: puts("oh green.
"); break;
case blue: puts("oh blue.
"); break;
default:
puts("这枚举还没数组好用 坑.
");
break;
}
return 0;
}
typedef声明
#include <stdio.h>
typedef unsigned char BYTE;
typedef char * STRING; // char指针
typedef struct book { // 可省去结构标记
char * title;
double value;
} MYBOOK;
int main(int argc, char *argv[])
{
BYTE x = 'A';
STRING ss = "you are beautiful";
printf("typedef BYTE en . %c %s
", x,ss);
MYBOOK mb = {
"aaa",10.01
};
printf("mb is %s
", mb.title);
return 0;
}
函数与指针
#include <stdio.h>
#include <ctype.h>
void to_upper(char *);
void to_lower(char *);
void show(void(*fp)(char *), char * str); //第一个参数为指向函数的指针
int main(int argc, char *argv[])
{
char name[10] = "AAaa";
void(*funcp)(char *); // 函数指针的定义、赋值
funcp = to_upper;
show(funcp, name); // 传递函数指针
funcp = to_lower;
show(funcp, name);
return 0;
}
void to_upper(char * str)
{
while (*str)
{
*str = toupper(*str);
str++;
}
}
void to_lower(char * str)
{
while (*str)
{
*str = tolower(*str);
str++;
}
}
void show(void(*fp)(char *), char * str)
{
(*fp)(str); //函数指针的使用 fp(str)亦可
printf("str is : %s
", str);
}