1.结构体的计算//struct BBB{
//long a;
//char c1;
//char c2;
//long b;
//long c;
//}*p;//sizeof(struct BBB)=16;
//int main()
//{
//p = (struct BBB*)0x100000;
//printf("0x%x", p + 0x1);//加整个结构体大小为0x10010
//printf(" 0x%x",(unsigned long) p + 0x1);//整型加1,0x100001
//printf(" 0x%x", (unsigned long*)p + 0x1);//加sizeof(unsigned long)*1,为0x100004
//printf(" 0x%x",(char *) p + 0x1);//加sizeof(char)*1,为0x100001
//system("pause");
//return 0;
//}
2.结构体中结构体,共用体中结构体的大小//union AAA{
//struct {
//char c1;
//short sl;
//char c2;
//}half;
//short kk;
//}number;
//struct BBB{
//char ucFirst;
//short us;
//char c2;
//short uo;
//}half;
//struct tagCCC
//{
//struct
//{
//char c1;
//short sl;
//char c2;
//}half;
//long kk;
//};//结构体是个整体按4对齐6+4=10,short和long中最大所占字节为4,4的整数倍为12
//int main()
//{
//printf("%d %d %d\n", sizeof(union AAA), sizeof(struct BBB), sizeof(struct tagCCC));
//system("pause");
//return 0;
//}
执行结果:
1字节对齐:4 6 8
4字节对齐:6 8 12
3.如果case语句中没有break,那么它之后的语句都会被执行。
4.指针和const的声明:
(1)指针所指对象是可读的
const int *p;
int const *p;
(2)指针是可读的
int *const p;
(3)指针和指针所指对象都是可读的
const int * const p;
int const *constp;
5.动态开辟void GetMemory(char *p,int len)
{
p=(char *)malloc(len);
}
int main()
{
char *p;
GetMemory(p,10);
strcpy(p,"bit");
printf("%s",p);
free(p);
}
上述代码有三处错误!!!
a.此时调用函数p动态开辟和主函数p所指不是同一个地方,因为p只是临时拷贝,没传地址过去。
b.strcpy,出现错误,此时p无指向。
c.free时并未将其开辟(临时变量)的释放,且应在free后让指针指向空。
正确代码为:void GetMemory(char **p,int len)
{
*p=(char *)malloc(len);
}
int main()
{
char *p;
GetMemory(&p,10);
strcpy(p,"bit");
printf("%s",p);
free(p);
p=NULL;
}
原文:http://10541556.blog.51cto.com/10531556/1698559