一 const
const char *, char const *, char * const,char const * const
const :常量 = final
//从右往左读
//P是一个指针 指向 const char类型
char str[] = "hello";
const char *p = str;
str[0] = 'c'; //正确
p[0] = 'c'; //错误 不能通过指针修改 const char
//可以修改指针指向的数据
//意思就是 p 原来 指向david,
//不能修改david爱去天之道的属性,
//但是可以让p指向lance,lance不去天之道的。
p = "12345";
//性质和 const char * 一样
char const *p1;
//p2是一个const指针 指向char类型数据
char * const p2 = str;
p2[0] = 'd'; //正确
p2 = "12345"; //错误
//p3是一个const的指针变量 意味着不能修改它的指向
//同时指向一个 const char 类型 意味着不能修改它指向的字符
//集合了 const char * 与 char * const
char const* const p3 = str;
二 typedef
就是别名,类似java 代理
并没有创建新的数据类型,只是给现有类型创建了别名
typedef int _in;
typedef char * string;
typedef int(*PFI)(char *, char *);
typedef Tnode * Treeptr;
typedef struct Tnode {
char *word;
int count;
Treeptr left;
Treeptr right;
} BinaryTreeNode;
int fun(char *, char *) {
return 0;
}
int test4() {
_in a = 20;
printf("%d\n", a);
string str;
str = (char *)"hello world";
PFI fp;
fp = fun;
char * ch;
ch = (char *)"hello world";
BinaryTreeNode* node;
node = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
system("pause");
return 0;
}
三 union 共用体
在相同的内存位置存储不同的数据类型
共用体占用的内存应足够存储共用体中最大的成员
成员共用一段内存,内存地址一致;最近定义的才有效
//占用4字节
union Data
{
int i;
short j;
}
union Data data;
data.i = 1;
//i的数据损坏
data.j = 1.1f;
Demo
union MyUnion {
int a;
char b;
float c;
};
int test4() {
MyUnion unio;
unio.a = 10;
unio.b = 'a';
unio.c = 1.2f;
printf("a: %#x, b: %#x, c: %#x\n", &unio.a, &unio.b, &unio.c);
printf("a: %d, b: %c, c: %f\n", unio.a, unio.b, unio.c);
system("pause");
return 0;
}
运行结果:
a: 0x8ff660, b: 0x8ff660, c: 0x8ff660
a: 1067030938, b: ? c: 1.200000