预处理 const 与 sizeof

来源:互联网 发布:网络运维工具 编辑:程序博客网 时间:2024/05/22 09:46

/***********************************《程序员面试宝典》第二版笔记*******************************************/

宏定义1. 用一个宏定义FIND求一个结构体struct里任意变量相对struct的偏移量struct student{int a;char b[20];double c;};则FIND(student, a);//等于0FIND(student, b);//等于4答:#define FIND(struc, e)(size_t)&(((struct*)0)->e)2. 用预处理指令#define 声明一个常数,用以表明1年中有多少秒?答:#define SECONDS_PER_YEAR (60*60*24*365)UL3. 写一个“标准”宏MIN这个宏输入两个参数并返回较小的一个答:#define MIN(a, b) ((a) < (b) ? (a) : (b) )const4. What does the keyword "const" means in C program? Please at least maketwo examples about the usage of const答:1)定义常量2)修饰函数参数3)修饰函数返回值5. const与#define 相比有什么不同?答:const常量有数据类型,宏常量没有数据类型sizeof6. What is the output of the following code?#include <stdio.h>#include <string.h>struct {short a1;short a2;short a3;}A;//2字节对齐结果为6struct {long a1;short a2;}B;//4字节对齐结果为8int main(){char* ss1 = "0123456789";//ss1是一个字符指针为4字节char ss2[] = "0123456789";//字符数组,加上隐含的"\0",为11char ss3[100] = "0123456789";//字符数组预分配100 * 1 = 100int ss4[100];//整形数组预分配100 * 4 = 400char q1[]="abc";//与ss2类似为4char q2[] = "a\n";//\n也算一做一位,为3个字节char* q3 = "a\n";//字符指针为4char *str1 = (char *)malloc(100);//指针为4void *str2 = (void *)malloc(100);//指针为4printf("sizeof(ss1)=%d, sizeof(ss2)=%d, sizeof(ss3)=%d, sizeof(ss4)=%d\n",sizeof(ss1), sizeof(ss2), sizeof(ss3), sizeof(ss4));printf("sizeof(q1)=%d, sizeof(q2)=%d, sizeof(q3)=%d\n", sizeof(q1), sizeof(q2), sizeof(q3));printf("sizeof(A)=%d, sizeof(B)=%d\n", sizeof(A), sizeof(B));printf("sizeof(str1)=%d, sizeof(str2)=%d\n", sizeof(str1), sizeof(str2));}7. 求下面程序的结果#include <iostream.h>class A1{public:int a;static int b;A1();~A1();}; //4因为static是静态变量存放在全局数据区的,而sizeof计算栈中分配的大小,是不会计算在内的class A2{public:int a; //4char c;//4字节对齐A2();~A2();};//8class A3{public:float a;//4char c;//4A3();~A3();};//8class A4{public:float a;//4int b;//4char c;//4A4();~A4();};//12class A5{public:double d;//8float a;//4int b;//4char c;//1A5();~A5();};//24int main(){cout << sizeof(A1)<<endl;cout << sizeof(A2)<<endl;cout << sizeof(A3)<<endl;cout << sizeof(A4)<<endl;cout << sizeof(A5)<<endl;}8. sizeof 和strlenchar *ss = "0123456789";printf("sizeof(ss)=%d, sizeof(*ss)=%d\n", sizeof(ss), sizeof(*ss));答:sizeof(ss) = 4,因为ss是指向字符串常量的字符指针    sizeof(*ss) = 1, 因为*ss是第一个字符9. char ss[100] = "0123456789";printf("sizeof(ss)=%d, strlen(ss)=%d\n", sizeof(ss), strlen(ss));答:sizeof(ss) = 1 * 100 = 100,内存中预分配    strlen(ss) = 10,它的内部实现是用一个循环计算字符串的长度,直到"\0"为止10. int ss[100] = "0123456789";printf("sizeof(ss)=%d, strlen(ss)=%d\n", sizeof(ss), strlen(ss));答:sizeof(ss) = 4 * 100 = 400, strlen(ss)错误,因为strlen参数只能是char型11. char var [10];int test(char var[]){return sizeof(var);//返回4,因为var[]已经退化成一个指针}int main(){int len = 0;printf("len=%d\n", test(var));return 0;}12. 一个空类占多少空间?多重继承的空类呢?答:一个空类占空间为1, 多重继承的空类所占空间还是1.13.内联函数和宏的差别答:1)内联函数要做参数类型检查,宏不用只是简单替代2)内联函数更安全可靠