1.
int _tmain(int argc, _TCHAR* argv[])
{
int i;
char unData[100];
short cOut;
for (i = 0; i < 100; i++)
{
unData[i] = i;
}
int *a = (int*)unData + 1;
short *b = (short*)a;
cOut = *(short*)((int*)unData + 1); //1284
return 0;
}
unData是unData[100]的首地址,(int*)unData + 1则是将地址加1后强制转换为int型指针,也就是步进4个字节,到达unData[4]
for 循环结束后unData[100]里的数据是十六进制的0x00,0x01, 0x02,0x03,0x04,0x05,0x06,....
转换成short时低位地址被截断,就是取0x04,0x05两个字节
CPU是小端模式,低位字节在内存的低地址端,高位字节在内存的高地址端,所以数据是0x0504,转换成是十进制为1284
2. 判断下列条件下的samples++_____,*samples++____操作可行与否
1) int * samples
2) const int *samples samples //const在星号前,const修饰指针所指向的变量,也就是指针的内容不可变
3) int * const samples //const在星号后,const修饰指针本身,指针不可变,但指针所指向的内容可变;且指针在定义时必须初始化。
4) const int *const samples //指针和指针所指向的内容都不可变,指针在定义时必须初始化
5)volatile const int *const samples //将一个变量声明为volatile,说明这个变量可能会被意想不到地改变的,这时编译器就不会去假设这个变量的值。
也就是说在使用到这个变量时每次都会小心地重新读取它的值。一个变量可以既是volatile也是const,是volatile说明它可能会被意想不到地改变,是const说明程序不应主动去修改它,如只读状态的寄存器。
*samples++ 等價 *samples; samples++
所以1)是二者均可,2)是samples++不可,*samples++可,3)是samples++不可,*samples++不可
4)5)是均不可
3. count the number of “1” in a word(32 bits)(10 points)
unsigned int countones(char data)
{
int n = 0;
while (data)
{
data = data & (data - 1);
n++;
}
return n;
}
4. The following codes calculate the dot product of A and B and save the result to Res. Please point out the possible problems of the codes(10 points)
int DotProduct(const short *A,int sizeA,const short *B int sizeB, const short *Res)
{
int i;/* loop counters*/
for(i=0;i<sizea;i++)
{
*Res = (*A++) * (*B++);
}
}
A,B,Res所指向的内容是只读,*Res的内容不能随意改变
*A++等价于*A, A++, *A * *B有溢出的风险
函数没有返回值
5. 分析代码输出(这么古老的写法还有。。。)
static char *olds;
size_t function1(s, accept) //没分号, s的内容是const修饰的常量
const char *s;
const char *accept;
{
const char *p;
const char *a;
size_t count = 0;
for (p = s; *p != ’\0’; ++p)
{
for (a = accept; *a != ’\0’; ++a)
if (*p == *a)
break;
if (*a == ’\0’)
return count;
else
++count;
}
return count;
har *function2(s, accept)
const char *s;
const char *accept;
while (*s != ’\0’)
{
const char *a = accept;
while (*a != ’\0’)
if (*a++ == *s)
return(char *)s;
++s;
}
return NULL;
}
char * function3(s, delim)
char *s;
const char *delim;
{
char *token;
if (s == NULL)
s = olds;
s += function1(s, delim);
if (*s == ’\0’)
{
olds = s;
return NULL;
}
return token;
}
int _tmain(int arge, char *argv[])
{
char s[] = *-abc -= -def = g*;
char *str1;
str1 = function3(s, ” - ”);
printf{ “str1 = %s\n”, str1 };
str1 = function3(NULL, ” -= ”);
printf{ “str1 = %s\n”, str1 };
str1 = function3(NULL, ” = ”)
printf{ “str1 = %s\n”, str1 };
printf{ “s = %s\n”, s };
return 0
}