第一题
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[5] = { 1, 2, 3, 4, 5 };
int *ptr = (int *)(&a + 1);
printf("%d,%d", *(a + 1), *(ptr - 1));
system("pause");
return 0;
}
(a+1)是向后移动一个(int)类型,即4个字节,指向元素2,解引用之后为2
(&a+1)是+1是跳过整个数组,现在ptr指向5后面的地址,*(ptr-1)是ptr+(-1)向前移动sizeof(int)个字节,即四个字节,现在指向5这个元素,解引用之后为5
第二题
#include<stdio.h>
#include<stdlib.h>
struct Test
{
int Num;
char *pcName;
short sDate;
char cha[2];
short sBa[4];
}*p;
int main()
{
p = (struct Test*)0x100000;
printf("%x\n", (struct Test *)p + 0x1);
printf("%x\n", (unsigned long)p + 0x1);
printf("%x\n", (unsigned int *)p + 0x1);
system("pause");
return 0;
}
这个结构体占20个字节,p强制类型转换成(struct Test *)之后+1,就是加sizeof(struct Test ),加20,换成16进制为14,答案为100014
p强制类型转换成(unsigned long),即转换成整形,整形加1,就直接加1,答案为100001
p强制类型转换成(unsigned int *),加1就是加sizeof(unsigned int),即4个字节,答案为100004
第三题
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[4] = { 1, 2, 3, 4 };
int *ptr1 = (int *)(&a + 1);
int *ptr2 = (int *)((int)a + 1);
printf("%x,%x", ptr1[-1], *ptr2);
system("pause");
return 0;
}
(&a+1)强制类型转换为int*,指向4后面的地址,ptr[-1]就是ptr+(-1),向前移动(int)个字节,指向元素4,答案为4
(int)a强制理性转换为int类型,加1向后移动一个字节,((int)a+1)强制类型转换为int*,指向了数组的第2个到第5个字节,即00 00 00 02 ,由于是小端存储为02 00 00 00 答案为200000
第四题
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[3][2] = { (0, 1), (2, 3), (4, 5) };
int *p;
p = a[0];
printf("%d\n", p[0]);
system("pause");
return 0;
}
此题特别注意的是括号还有里面的逗号表达式,逗号表达式的最后一个结果作为整个式子的结果,此题答案为1
第五题
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[5][5];
int(*p)[4];
p = a;
printf("%p,%d\n", &p[4][2] - &a[4][2], &p[4][2] - &a[4][2]);
system("pause");
return 0;
}
–4的原码是:10000000 00000000 00000000 00000100
反码为:11111111 11111111 11111111 11111011
补码为:11111111 11111111 11111111 11111100
所以为:ff ff ff fc
第六题
#include<stdio.h>
#include<stdlib.h>
int main()
{
int aa[2][5] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *ptr1 = (int *)(&aa + 1);
int *ptr2 = (int *)(*(aa + 1));
printf("%d,%d", *(ptr1 - 1), *(ptr2 - 1));
system("pause");
return 0;
答案为10 和5
第七题
(*( void(*) ()) 0)();
调用0地址处的函数,调用的函数的参数是无参,返回类型为void
void (*signal(int , void (*)(int)))(int);
signal是一个函数声明,函数的参数为int和一个函数指针,
该函数指针指向的函数的参数为int,返回类型为void,
signal函数的返回类型也为一个函数指针,
该函数指针指向的函数的参数为int,返回类型为void
第八题
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *a[] = { "work", "at", "alibaba" };
char**pa = a;
pa++;
printf("%s\n", *pa);
system("pause");
return 0;
}
a数组里面保存的是字符串的首地址
pa保存的是数组a的地址,pa++指向了a[1]的地址,解引用之后为a[1],输出为at
第九题
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *c[] = { "ENTER", "NEW", "POINT", "FIRST" };
char**cp[] = { c + 3, c + 2, c + 1, c };
char***cpp = cp;
printf("%s\n", **++cpp);
printf("%s\n", *--*++cpp + 3);
printf("%s\n", *cpp[-2] + 3);
printf("%s\n", cpp[-1][-1] + 1);
system("pause");
return 0;
}
**++cpp
cpp指向了cp[1],cp[1]指向c[2]为ENTER
“`
–++cpp + 3
cpp指向了cp[2],cp]2]减-1指向了c,在+3,为ER
```
*cpp[-2] + 3
cpp[-1]指向了cp,cp指向c[3],+3为ST
cpp[-1][-1] + 1
cpp[-1]指向cp[1],cp[-1]指向c+1,+1,为EW