面试杂项题

编写strcat函数

已知strcat函数的原型是char *strcat (char *strDest, const char *strSrc);
其中strDest 是目的字符串,strSrc 是源字符串。
(1)不调用C++/C 的字符串库函数,请编写函数 strcat
答:
VC源码:
char * __cdecl strcat (char * dst, const char * src)
{
char * cp = dst;
while( *cp )
cp++; /* find end of dst */
while( *cp++ = *src++ ) ; /* Copy src to end of dst */
return( dst ); /* return dst */
}
(2)strcat能把strSrc 的内容连接到strDest,为什么还要char * 类型的返回值?
答:方便赋值给其他变量

不用任何局部和全局变量实现int strlen(char *a)

#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <iostream>
using namespace std;
/*int strlen(char *a)
{
	if (0 == *a)
		return 0;
	else
		return strlen(++a) + 1;
}*/
int strlen(char *a)
{   
	if(0 == *a)
		return  0;   
	else 
		return  1 + strlen(a +1);
}
int main(void)
{
	char *p="1234567";
	cout<<strlen(p)<<endl;
	system("pause");
	return 0;
}

判断一段程序是由C 编译程序还是由C++编译程序编译

#ifdef __cplusplus
cout<<"c++";
#else
cout<<"c";
#endif

2.C++中delete和delete[]的区别
C++告诉我们在回收用 new 分配的单个对象的内存空间的时候用 delete,回收用 new[] 分配的一组对象的内存空间的时候用 delete[]。
关于 new[] 和 delete[],其中又分为两种情况:(1) 为基本数据类型分配和回收空间;(2) 为自定义类型分配和回收空间。 
请看下面的程序。

#include <iostream>;
using namespace std;
class T 
{
public:
	T() 
	{ 
		cout << "constructor" << endl;
	}
	~T() 
	{
		cout << "destructor" << endl;
	}
};
int main()
{
	const int NUM = 3;
	T* p1 = new T[NUM];
	delete[] p1;
	//delete p1;
	system("pause");
} 

大家可以自己运行这个程序,看一看 delete p1 和 delete[] p1 的不同结果,我就不在这里贴运行结果了。
从运行结果中我们可以看出,delete p1 在回收空间的过程中,只有 p1[0] 这个对象调用了析构函数,其它对象如 p1[1]、p1[2] 等都没有调用自身的析构函数,这就是问题的症结所在。如果用 delete[],则在回收空间之前所有对象都会首先调用自己的析构函数。
基本类型的对象没有析构函数,所以回收基本类型组成的数组空间用 delete 和 delete[] 都是应该可以的;但是对于类对象数组,只能用 delete[]。对于 new 的单个对象,只能用 delete 不能用 delete[] 回收空间。
所以一个简单的使用原则就是:new 和 delete、new[] 和 delete[] 对应使用。

数组与指针的区别
数组要么在静态存储区被创建(如全局数组),要么在栈上被创建。指针可以随时指向任意类型的内存块。
(1)修改内容上的差别
char a[] = “hello”;
a[0] = ‘X’;
char *p = “world”; // 注意p 指向常量字符串
p[0] = ‘X’; // 编译器不能发现该错误,运行时错误
(2) 用运算符sizeof 可以计算出数组的容量(字节数)。sizeof(p),p 为指针得到的是一个指针变量的字节数,而不是p 所指的内存容量。C++/C 语言没有办法知道指针所指的内存容量,除非在申请内存时记住它。注意当数组作为函数的参数进行传递时,该数组自动退化为同类型的指针。
char a[] = "hello world";
char *p = a;
cout<< sizeof(a) << endl; // 12 字节
cout<< sizeof(p) << endl; // 4 字节
计算数组和指针的内存容量

void Func(char a[100])
{
cout<< sizeof(a) << endl; // 4 字节而不是100 字节
}

给出程序的输出结果 .

#include <iostream>
using namespace std;
struct A
{
	A()
	{
		std::cout << "A";
	}
};
struct B: public A
{
	B()
	{
		std::cout << "B";
	}
};
struct C
{
	C()
	{
		std::cout << "C";
	}
	B b;
	A a;
};
int main()
{
	C c;
	cout<<endl;
	system("pause");
	return 0;
}
//ABAC




 

原文地址:https://www.cnblogs.com/byfei/p/14104693.html