面试题1
以下代码的输出结果是什么?
- char str1[] = "abc";
- char str2[] = "abc";
- const char str3[] = "abc";
- const char str4[] = "abc";
- const char *str5 = "abc";
- const char *str6 = "abc";
- char *str7 = "abc";
- char *str8 = "abc";
- cout << ( str1 == str2 ) << endl;
- cout << ( str3 == str4 ) << endl;
- cout << ( str5 == str6 ) << endl;
- cout << ( str7 == str8 ) << endl;
解析:结果为0 0 1 1。
因为str1、str2、str3、str4 是数组变量,它们有各自的内存空间;而str5、str6、str7、str8是指针,它们指向相同的常量区域。
面试题2
简述数组和指针的区别。
解析:任何一个C/C++程序员都应该能够清晰地指出数组和指针的以下三点区别:
1. 数组要么在静态存储区被创建(如全局数组),要么在栈上被创建;指针可以随时指向任意类型的内存块。
2. 修改内容上的区别,如:
- char a[] = "hello";
- a[0] = "A'; //编译不会出错,a[0]会被成功赋值。
- char *p = "world"; //p 指向常量字符串。
- p[0] = "A"; //运行时会出错。
3. 用运算符sizeof 可以计算出数组的容量(字节数);sizeof(p),p 为指针,得到的是一个指针变量的字节数,而不是p 所指的内存容量,C/C++语言没有办法知道指针所指的内存容量,除非在申请内存时记住它。当数组作为函数的参数进行传递时,该数组自动退化为同类型的指针。
面试题3
文件中有一组整数,写出完整代码请将其排序后输出到另一个文件中。
解析:这题难度不大,考的重点不在算法,也不在思路,而在于面试者能否现场写出完全可以编译运行的代码。
- #include<iostream>
- #include<fstream>
- using namespace std;
- void Order(vector<int>& data) //bubble sort
- {
- int count = data.size();
- int tag = false; // 设置是否需要继续冒泡的标志位
- for ( int i = 0; i < count; i++)
- {
- for ( int j = 0; j < count-i-1; j++)
- {
- if ( data[j] > data[j+1])
- {
- tag = true;
- int temp = data[j];
- data[j] = data[j+1];
- data[j+1] = temp;
- }
- }
- if ( !tag )
- break;
- }
- }
- void main( void )
- {
- vector<int>data;
- ifstream in("c:\\data.txt");
- if ( !in)
- {
- cout<<"file error!";
- exit(1);
- }
- int temp;
- while (!in.eof())
- {
- in>>temp;
- data.push_back(temp);
- }
- in.close(); //关闭输入文件流
- Order(data);
- ofstream out("c:\\result.txt");
- if ( !out)
- {
- cout<<"file error!";
- exit(1);
- }
- for ( i = 0; i < data.size(); i++)
- out<<data<<" ";
- out.close(); //关闭输出文件流
- }



