/***********************************《程序员面试宝典》第二版笔记*******************************************/
宏定义
1. 用一个宏定义FIND求一个结构体struct里任意变量相对struct的偏移量
struct student
{
int a;
char b[20];
double c;
};
则FIND(student, a);//等于0
FIND(student, b);//等于4
答:#define FIND(struc, e)(size_t)&(((struct*)0)->e)
2. 用预处理指令#define 声明一个常数,用以表明1年中有多少秒?
答:#define SECONDS_PER_YEAR (60*60*24*365)UL
3. 写一个“标准”宏MIN这个宏输入两个参数并返回较小的一个
答:#define MIN(a, b) ((a) < (b) ? (a) : (b) )
const
4. What does the keyword "const" means in C program? Please at least make
two examples about the usage of const
答:1)定义常量
2)修饰函数参数
3)修饰函数返回值
5. const与#define 相比有什么不同?
答:const常量有数据类型,宏常量没有数据类型
sizeof
6. What is the output of the following code?
#include <stdio.h>
#include <string.h>
struct {
short a1;
short a2;
short a3;
}A;//2字节对齐结果为6
struct {
long a1;
short a2;
}B;//4字节对齐结果为8
int main()
{
char* ss1 = "0123456789";//ss1是一个字符指针为4字节
char ss2[] = "0123456789";//字符数组,加上隐含的"\0",为11
char ss3[100] = "0123456789";//字符数组预分配100 * 1 = 100
int ss4[100];//整形数组预分配100 * 4 = 400
char q1[]="abc";//与ss2类似为4
char q2[] = "a\n";//\n也算一做一位,为3个字节
char* q3 = "a\n";//字符指针为4
char *str1 = (char *)malloc(100);//指针为4
void *str2 = (void *)malloc(100);//指针为4
printf("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; //4
char c;//4字节对齐
A2();
~A2();
};//8
class A3
{
public:
float a;//4
char c;//4
A3();
~A3();
};//8
class A4
{
public:
float a;//4
int b;//4
char c;//4
A4();
~A4();
};//12
class A5
{
public:
double d;//8
float a;//4
int b;//4
char c;//1
A5();
~A5();
};//24
int main()
{
cout << sizeof(A1)<<endl;
cout << sizeof(A2)<<endl;
cout << sizeof(A3)<<endl;
cout << sizeof(A4)<<endl;
cout << sizeof(A5)<<endl;
}
8. sizeof 和strlen
char *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)内联函数更安全可靠