现在的位置: 首页 > 综合 > 正文

ForSecondWork-No.4:C/C++笔试题回忆并整理

2014年09月05日 ⁄ 综合 ⁄ 共 2173字 ⁄ 字号 评论关闭

1、写出下列代码的运行结果。

void GetMemory(char *p,int num)

{

    p=(char *) malloc(sizeof(char)*num);

}

int main(int argc , char * argv[])

{

   char *str=NULL;

   GetMemory(str,100);

   strcpy(str,"Hello World");

   cout<<str<<endl;

}

       答:这是C++内存管理方面的问题。

       程序运行崩溃并泄露了一块内存。关键是调用GetMemory不能使str指向存储100个字符的内存空空间。详解请参考C++内存管理相关知识。编译器总是要为函数的每个参数制作临时副本,指针参数 p 的副本是 _p,
编译器使 _p = p。如果函数体内的程序修改了_p 的内容,就导致参数 p 的内容作相应的修改。这就是指针
可以用作输出参数的原因。在本例中,_p 申请了新的内存,只是把_p 所指的内存地址改变了,但是 p 丝毫
未变。所以函数 GetMemory 并不能输出任何东西。事实上,每执行一次 GetMemory 就会泄露一块内存,因为没有用 free 释放内存。如果非得要用指针参数去申请内存,那么应该改用“指向指针的指针”。


2、 实现如下函数

        这个题目还是很具有代表行的,我全错,除了析构函数。


#include <iostream>
#include <string>
#include <vector>
using namespace std;

class CString
{
public:
	CString(const char* str = NULL);
	CString(const CString &other);
	~CString();
	CString & operator = (const CString &other);
	

public:
	char *m_data;
};

CString::~CString()
{
	delete []m_data;
}
CString::CString(const char*str)
{
	if (str == NULL)
	{
		m_data = new char[1];
		*m_data = '\0';
	}
	else
	{
		int length = strlen(str);
		m_data = new char[length + 1];
		strcpy(m_data, str);
	}
}

CString::CString(const CString &other)
{
	cout<<"Copy Constructor is defined by user!"<<endl;
	int length = strlen(other.m_data);
	m_data = new char[length + 1];
	strcpy(m_data, other.m_data);
}

CString &CString::operator =(const CString &other)
{
	if (this == &other)//s1 = s1, then this will EQUAL to address of other
	{
		return *this;
	}
	//free all memory, then distribute new memory
	delete []m_data;
	int length = strlen(other.m_data);
	m_data = new char[length + 1];
	strcpy(m_data, other.m_data);
	return *this;
}

int main()
{
	CString str("hello");
	CString s1("hello");
	CString s2;
	s1 = s1;
	s2 = str;

	cout<<str.m_data<<" "<<s2.m_data<<endl;

	vector<char> myVec;
	char ch;
	while( (ch = getchar()) != EOF)
	{
		myVec.push_back(ch);
	}

	vector<char>::iterator itr = myVec.begin();
	while (itr != myVec.end())
	{
		cout << *itr++ << endl;
	}

	return 0;
}


3、编程题:两个增序的int数组a,b合并为仍然增序的int数组c。

     答:void MergeShuzu( int a[] , int m , int b[] , int n , int c[] )。

     没有新意。

4、编程题:求n!后末尾零的个数。

      答:int CountZeros( int n )。

      两点:求n!和求末尾零的个数,都不难。


5、写出下列程序运行的结果。

     a.指针使用

        普通的很,略。

     b.可能涉及高低位

        答:代码如下,我还没弄懂他想考我什么,从觉得不可能这么简单。代码可能有些不同,不能全记起,因为不知道出这题的用意,所以记忆更不全了。

char c=0;

int i=0;

while(i<128)

{

    i++;

}

printf("%d %d",c,i);

for(;i<255;i++,c=i);

printf("%d %d",c,i);

     c.动态联编

        参见博文:动态联编也就是此博文中的晚绑定。


另附上以前遇到的两个面试题

面试题-1:虚函数表

参见博文:http://blog.csdn.net/jandunlab/article/details/16920925

面试题-2:C++多态有哪些

抱歉!评论已关闭.