0 Comments

面试题:数组(1)

发布于:2012-11-30  |   作者:广州网站建设  |   已聚集:人围观

面试题1

以下代码的输出结果是什么?


  1. char str1[] = "abc";  
  2. char str2[] = "abc";  
  3. const char str3[] = "abc";  
  4. const char str4[] = "abc";  
  5. const char *str5 = "abc";  
  6. const char *str6 = "abc";  
  7. char *str7 = "abc";  
  8. char *str8 = "abc";  
  9. cout << ( str1 == str2 ) << endl;  
  10. cout << ( str3 == str4 ) << endl;  
  11. cout << ( str5 == str6 ) << endl;  
  12. cout << ( str7 == str8 ) << endl

解析:结果为0 0 1 1。

因为str1、str2、str3、str4 是数组变量,它们有各自的内存空间;而str5、str6、str7、str8是指针,它们指向相同的常量区域。

面试题2

简述数组和指针的区别。

解析:任何一个C/C++程序员都应该能够清晰地指出数组和指针的以下三点区别:

1. 数组要么在静态存储区被创建(如全局数组),要么在栈上被创建;指针可以随时指向任意类型的内存块。

2. 修改内容上的区别,如:


  1. char a[] = "hello";  
  2. a[0] = "A'; //编译不会出错,a[0]会被成功赋值。  
  3. char *p = "world"; //p 指向常量字符串。  
  4. p[0] = "A"; //运行时会出错。 

3. 用运算符sizeof 可以计算出数组的容量(字节数);sizeof(p),p 为指针,得到的是一个指针变量的字节数,而不是p 所指的内存容量,C/C++语言没有办法知道指针所指的内存容量,除非在申请内存时记住它。当数组作为函数的参数进行传递时,该数组自动退化为同类型的指针。

面试题3

文件中有一组整数,写出完整代码请将其排序后输出到另一个文件中。

解析:这题难度不大,考的重点不在算法,也不在思路,而在于面试者能否现场写出完全可以编译运行的代码。


  1. #include<iostream> 
  2. #include<fstream> 
  3. using namespace std;  
  4. void Order(vector<int>& data) //bubble sort  
  5. {  
  6. int count = data.size();  
  7. int tag = false; // 设置是否需要继续冒泡的标志位  
  8. for ( int i = 0; i < count; i++)  
  9. {  
  10. for ( int j = 0; j < count-i-1; j++)  
  11. {  
  12. if ( data[j] > data[j+1])  
  13. {  
  14. tag = true;  
  15. int temp = data[j];  
  16. data[j] = data[j+1];  
  17. data[j+1] = temp;  
  18. }  
  19. }  
  20. if ( !tag )  
  21. break;  
  22. }  
  23. }  
  24. void main( void )  
  25. {  
  26. vector<int>data;  
  27. ifstream in("c:\\data.txt");  
  28. if ( !in)  
  29. {  
  30. cout<<"file error!";  
  31. exit(1);  
  32. }  
  33. int temp;  
  34. while (!in.eof())  
  35. {  
  36. in>>temp;  
  37. data.push_back(temp);  
  38. }  
  39. in.close(); //关闭输入文件流  
  40. Order(data);  
  41. ofstream out("c:\\result.txt");  
  42. if ( !out)  
  43. {  
  44. cout<<"file error!";  
  45. exit(1);  
  46. }  
  47. for ( i = 0; i < data.size(); i++)  
  48. out<<data<<" ";  
  49. out.close(); //关闭输出文件流  
标签:
飞机