最终的胜利
专题七:最终的胜利。包括以下章节:
- 你懂C,请进军C++的世界
- 笑傲面试
- 简历编写及面试技巧解析
实例分析2-1: 指针运算
2-1.c
#include <stdio.h>
void main()
{
int TestArray[5][5] = { {11,12,13,14,15},
{16,17,18,19,20},
{21,22,23,24,25},
{26,27,28,29,30},
{31,32,33,34,35}
};
//==>p1指向数组TestArray的下一个地址
int* p1 = (int*)(&TestArray + 1);
//TestArray类型是int(*)[5]
//TestArray+1指向TestArray[1]
//TestArray[1]类型是int(*)[5]
//*(TestArray[1])类型是int*
//==>&TestArray[1][0]+6==>&TestArray[2][1]
int* p2 = (int*)(*(TestArray + 1) + 6);
//1,*(*TestArray)==>*(*TestArray[0])==>*(&TestArray[0][0])==>11
//2,*(*(TestArray + 1))==>*(*TestArray[1])==>*(&TestArray[1][0])==>16
//3,*(*(TestArray+3)+3)==>*(*TestArray[3]+3)==>*(&TestArray[3][0]+3)==>*(&TestArray[3][4])==>29
//4,p1[-8]==>*(&TestArray[4][4]+1-8)==>*(&TestArray[3][3])==>28
//5,p2[4]==>*(&TestArray[2][1]+4)*(&TestArray[3][0])==>26
printf("Result: %d; %d; %d; %d; %d\n", *(*TestArray), *(*(TestArray + 1)),
*(*(TestArray + 3) + 3), p1[-8],
p2[4]);
}
结果:
实例分析2-2: 调试经验
2-2.c
#include<stdio.h>
void main()
{
char* p = "hello world!";
int a = (int)p;
short s = 'c';
//p指针指向 "hello world!"
//*p内容是{'h','e','l','l','o'...}
//%c取一个字节,取'h'
printf("%c\n", (long)(*((int*)p)));
//%s取字符串,有一个寻址过程;a寻址a的值指向的内存空间,也就是字符串 "hello world!"
printf("%s\n", a);
//%s取字符串,有一个寻址过程;&s的值是s的内存地址,也就是'c'的空间
printf("%s\n", &s);
}
结果:
实例分析2-3: 安全编程
2-3.c
#include<stdio.h>
int main(int argc, char *argv[])
{
int flag = 0;
char passwd[10];
memset(passwd,0,sizeof(passwd));
strcpy(passwd, argv[1]);
//如果argv[1]大于10个字节,越界;会写入flag空间,所以密码总是正确
//可以使用strncpy :strncpy(passwd, argv[1], 9);
if(0 == strcmp("LinuxGeek", passwd))
{
flag = 1;
}
if( flag )
{
printf("\n Password cracked \n");
}
else
{
printf("\n Incorrect passwd \n");
}
return 0;
}