据传是《中软国际2009校园招聘》笔试题(有改动by ASCE1885):
1)Swap two variables without using third variable?
解答:一开始容易陷入误区,认为交换必须通过移动变量来实现,因而少不了要用第三个变量,仔细想想,却有以下几种方法可以实现呢,基本思想是进行代数运算或逻辑上的变换(这里仅以基本内置类型int变量为例):
(1)简单的加法和减法运算:
函数形式:
void swap(int &a, int &b)
{
a += b;
b = a-b;
a = a-b;
}
宏定义:
#define swap(a, b) a+=b;b=a-b;a=a-b;
(2)异或方法,异或的特性是连续跟一个数异或两次得到的是它自身:
函数形式:
void swap(int &a, int &b)
{
a = a^b;
b = a^b; //相当于a连续跟b异或两次,即是a
a = a^b; //相当于b连续跟a异或两次,即是b
}
宏定义:
#define swap(a,b) a=a^b;b=a^b;a=a^b;
(3)带乘除的方法,此方法效率较低,乘除嘛!
函数形式:
void swap(int &a, int &b)
{
a = a+b;
b = a - 2*b;
a = (a-b)/2;
b = a+b;
}
宏定义:
#define swap(a, b) a=a+b;b=a-2*b;a=(a-b)/2;b=a+b;
2)what is wrong with the call fopen(“C:/newdir/file.dat”, “r”)?
解答:应该改为:fopen("C://newdir//file.dat", "r");
3)what is wrong with the following code?
char *p;
*p = malloc(10);
解答:应改为:
char *p;
p = (char*)malloc(10);
4)will the following program execute?
void main()
{
void* vptr = (void*)malloc(sizeof(void));
vptr++;
}
解答:不会,编译通不过,sizeof不能跟void;同时标准C++禁止对void指针进行增减操作。
5)以下程序运行结果是什么?
#include<iostream>
int main()
{
char a[] = "hello";
char *p = a;
std::cout<<sizeof(a)<<std::endl;
std::cout<<sizeof(p)<<std::endl;
std::cout<<strlen(a)<<std::endl;
std::cout<<strlen(p)<<std::endl;
system("pause");
return 0;
}
解答:6 4 5 5,当然是每行一个数了。