c语言面试常问题.docx

上传人:b****6 文档编号:6356105 上传时间:2023-01-05 格式:DOCX 页数:14 大小:23.80KB
下载 相关 举报
c语言面试常问题.docx_第1页
第1页 / 共14页
c语言面试常问题.docx_第2页
第2页 / 共14页
c语言面试常问题.docx_第3页
第3页 / 共14页
c语言面试常问题.docx_第4页
第4页 / 共14页
c语言面试常问题.docx_第5页
第5页 / 共14页
点击查看更多>>
下载资源
资源描述

c语言面试常问题.docx

《c语言面试常问题.docx》由会员分享,可在线阅读,更多相关《c语言面试常问题.docx(14页珍藏版)》请在冰豆网上搜索。

c语言面试常问题.docx

c语言面试常问题

已经n次倒在c语言面试的问题上,总结了一下,是由于基础知识不扎实。

痛定思痛,决定好好努力!

1.引言

  本文的写作目的并不在于提供C/C++程序员求职面试指导,而旨在从技术上分析面试题的内涵。

文中的大多数面试题来自各大论坛,部分试题解答也参考了网友的意见。

  许多面试题看似简单,却需要深厚的基本功才能给出完美的解答。

企业要求面试者写一个最简单的strcpy函数都可看出面试者在技术上究竟达到了怎样的程度,我们能真正写好一个strcpy函数吗?

我们都觉得自己能,可是我们写出的strcpy很可能只能拿到10分中的2分。

读者可从本文看到strcpy函数从2分到10分解答的例子,看看自己属于什么样的层次。

此外,还有一些面试题考查面试者敏捷的思维能力。

  分析这些面试题,本身包含很强的趣味性;而作为一名研发人员,通过对这些面试题的深入剖析则可进一步增强自身的内功。

2.找错题

  试题1:

voidtest1()

{

 charstring[10];

 char*str1="09";

 strcpy(string,str1);

}

  试题2:

voidtest2()

{

 charstring[10],str1[10];

 inti;

 for(i=0;i<10;i++)

 {

  str1[i]='a';

 }

 strcpy(string,str1);

}

  试题3:

voidtest3(char*str1)

{

 charstring[10];

 if(strlen(str1)<=10)

 {

  strcpy(string,str1);

 }

}

  解答:

  试题1字符串str1需要11个字节才能存放下(包括末尾的’\0’),而string只有10个字节的空间,strcpy会导致数组越界;

  对试题2,如果面试者指出字符数组str1不能在数组内结束可以给3分;如果面试者指出strcpy(string,str1)调用使得从str1内存起复制到string内存起所复制的字节数具有不确定性可以给7分,在此基础上指出库函数strcpy工作方式的给10分;

  对试题3,if(strlen(str1)<=10)应改为if(strlen(str1)<10),因为strlen的结果未统计’\0’所占用的1个字节。

  剖析:

  考查对基本功的掌握:

  

(1)字符串以’\0’结尾;

  

(2)对数组越界把握的敏感度;

  (3)库函数strcpy的工作方式,如果编写一个标准strcpy函数的总分值为10,下面给出几个不同得分的答案:

  2分

voidstrcpy(char*strDest,char*strSrc)

{

 while((*strDest++=*strSrc++)!

=‘\0’);

}

  4分

voidstrcpy(char*strDest,constchar*strSrc)

..功题

  试题1:

分别给出BOOL,int,float,指针变量与“零值”比较的if语句(假设变量名为var)

  解答:

   BOOL型变量:

if(!

var)

   int型变量:

if(var==0)

   float型变量:

   constfloatEPSINON=;

   if((x>=-EPSINON)&&(x<=EPSINON)

   指针变量:

  if(var==NULL)

  剖析:

  考查对0值判断的“内功”,BOOL型变量的0判断完全可以写成if(var==0),而int型变量也可以写成if(!

var),指针变量的判断也可以写成if(!

var),上述写法虽然程序都能正确运行,但是未能清晰地表达程序的意思。

  一般的,如果想让if判断一个变量的“真”、“假”,应直接使用if(var)、if(!

var),表明其为“逻辑”判断;如果用if判断一个数值型变量(short、int、long等),应该用if(var==0),表明是与0进行“数值”上的比较;而判断指针则适宜用if(var==NULL),这是一种很好的编程习惯。

  浮点型变量并不精确,所以不可将float变量用“==”或“!

=”与数字比较,应该设法转化成“>=”或“<=”形式。

如果写成if(x==,则判为错,得0分。

  试题2:

以下为WindowsNT下的32位C++程序,请计算sizeof的值

voidFunc(charstr[100])

{

 sizeof(str)=?

}

void*p=malloc(100);

sizeof(p)=?

  解答:

sizeof(str)=4

sizeof(p)=4

  剖析:

  Func(charstr[100])函数中数组名作为函数形参时,在函数体内,数组名失去了本身的内涵,仅仅只是一个指针;在失去其内涵的同时,它还失去了其常量特性,可以作自增、自减等操作,可以被修改。

  数组名的本质如下:

  

(1)数组名指代一种数据结构,这种数据结构就是数组;

  例如:

charstr[10];

cout<<sizeof(str)<<endl;

  输出结果为10,str指代数据结构char[10]。

  

(2)数组名可以转换为指向其指代实体的指针,而且是一个指针常量,不能作自增、自减等操作,不能被修改;

charstr[10];

str++;.*/

#ifdef__cplusplus

}

#endif

#endif/*__INCvxWorksh*/

  解答:

  头文件中的编译宏

#ifndef __INCvxWorksh

#define __INCvxWorksh

#endif

  的作用是防止被重复引用。

  作为一种面向对象的语言,C++支持函数重载,而过程式语言C则不支持。

函数被C++编译后在symbol库中的名字与C语言的不同。

例如,假设某个函数的原型为:

voidfoo(intx,inty);

  该函数被C编译器编译后在symbol库中的名字为_foo,而C++编译器则会产生像_foo_int_int之类的名字。

_foo_int_int这样的名字包含了函数名和函数参数数量及类型信息,C++就是考这种机制来实现函数重载的。

  为了实现C和C++的混合编程,C++提供了C连接交换指定符号extern"C"来解决名字匹配问题,函数声明前加上extern"C"后,则编译器就会按照C语言的方式将该函数编译为_foo,这样C语言中就可以调用C++的函数了。

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 试题5:

编写一个函数,作用是把一个char组成的字符串循环右移n个。

比如原来是“abcdefghi”如果n=2,移位后应该是“hiabcdefgh”

  函数头是这样的:

.

}

  解答:

  正确解答1:

voidLoopMove(char*pStr,intsteps)

{

 intn=strlen(pStr)-steps;

 chartmp[MAX_LEN];

 strcpy(tmp,pStr+n);

 strcpy(tmp+steps,pStr);

 *(tmp+strlen(pStr))='\0';

 strcpy(pStr,tmp);

}

  正确解答2:

voidLoopMove(char*pStr,intsteps)

{

 intn=strlen(pStr)-steps;

 chartmp[MAX_LEN];

 memcpy(tmp,pStr+n,steps);

 memcpy(pStr+steps,pStr,n);

 memcpy(pStr,tmp,steps);

}

  剖析:

  这个试题主要考查面试者对标准库函数的熟练程度,在需要的时候引用库函数可以很大程度上简化程序编写的工作量。

  最频繁被使用的库函数包括:

  

(1)strcpy

  

(2)memcpy

  (3)memset

Pre-interviewQuestions

Thesearequestionstoaskinaphoneinterview.Theideaistoqualifyapersonbeforebringingtheminforaface-to-facesession.

Whatisavirtualmethod?

Apurevirtualmethod?

Whenwouldyouuse/notuseavirtualdestructor?

Whatisthedifferencebetweenapointerandareference?

Areferencemustalwaysrefertosomeobjectand,therefore,mustalwaysbeinitialized;pointersdonothavesuchrestrictions.Apointercanbereassignedtopointtodifferentobjectswhileareferencealwaysreferstoanobjectwithwhichitwasinitialized.

Whatisthedifferencebetweennew/deleteandmalloc/free?

Malloc/freedonotknowaboutconstructorsanddestructors.Newanddeletecreateanddestroyobjects,whilemallocandfreeallocateanddeallocatememory.

Whatdoesconstmean?

Whatmethodsshouldeveryc++classdefineandwhy?

Whatdoesmainreturn?

Explainwhattheheaderforasimpleclasslookslike.

Howdoyouhandlefailureinaconstructor?

AccordingtoBjarneStroustup,designeroftheC++language,youhandlefailuresinaconstructorbythrowinganexception.Seehereformoredetails,includingalinktohisdocumentonexceptionsafetyandthestandardlibrary:

--------------------------------------------------------------------------------

JuniorQuestions

WhatisthedifferencebetweenCandC++?

Wouldyouprefertouseoneovertheother?

CisbasedonstructuredprogrammingwhereasC++supportstheobject-orientedprogrammingparadigm.Duetotheadvantagesinherentinobject-orientedprogramssuchasmodularityandreuse,C++ispreferred.HoweveralmostanythingthatcanbebuiltusingC++canalsobebuiltusingC.

Explainoperatorprecendence.

Operatorprecedenceistheorderinwhichoperatorsareevaluatedinacompoundexpression.Forexample,whatistheresultofthefollowingexpression?

6+3*4/2+2

Hereisacompoundexpressionwithaninsidiouserror.

while(ch=nextChar()!

='\0')

Theprogrammer'sintentionistoassignchtothenextcharacterthentestthatcharactertoseewhetheritisnull.Sincetheinequalityoperatorhashigherprecendencethantheassignmentoperator,therealresultisthatthenextcharacteriscomparedtonullandchisassignedthebooleanresultofthetest.0or1).

WhataretheaccessprivilegesinC++?

Whatisthedefaultaccesslevel?

TheaccessprivilegesinC++areprivate,publicandprotected.Thedefaultaccesslevelassignedtomembersofaclassisprivate.Privatemembersofaclassareaccessibleonlywithintheclassandbyfriendsoftheclass.Protectedmembersareaccessiblebytheclassitselfandit'ssub-classes.Publicmembersofaclasscanbeaccessedbyanyone.

Whatisdataencapsulation?

DataEncapsulationisalsoknownasdatahiding.Themostimportantadvantageofencapsulationisthatitletstheprogrammercreateanobjectandthenprovideaninterfacetotheobjectthatotherobjectscanusetocallthemethodsprovidedbytheobject.Theprogrammercanchangetheinternalworkingsofanobjectbutthistransparenttootherinterfacingprogramsaslongastheinterfaceremainsunchanged.

Whatisinheritance?

Inheritanceisamechanismthroughwhichasubclassinheritsthepropertiesandbehaviorofitssuperclass;thesubclasshasaISArelationshipwiththesuperclass.ForexampleVehiclecanbeasuperclassandCarcanbeasubclassderivedfromVehicle.InthiscaseaCarISAVehicle.Thesuperclass'isnota'subclassasthesubclassismorespecializedandmaycontainadditionalmembersascomparedtothesuperclass.Thegreatestadvantageofinheritanceisthatitpromotesgenericdesignandcodereuse.

Whatismultipleinheritance?

Whatareitsadvantagesanddisadvantages?

MultipleInheritanceistheprocesswherebyasub-classcanbederivedfrommorethanonesuperclass.Theadvantageofmultipleinheritanceisthatitallowsaclasstoinheritthefunctionalityofmorethanonebaseclassthusallowingformodelingofcomplexrelationships.Thedisadvantageofmultipleinheritanceisthatitcanleadtoalotofconfusionwhentwobaseclassesimplementamethodwiththesamename.

Whatispolymorphism?

Polymorphismreferstotheabilitytohavemorethanonemethodwiththesamesignatureinaninheritancehierarchy.Thecorrectmethodisinvokedatrun-timebasedonthecontext(object)onwhichthemethodisinvoked.Polymorphismallowsforagenericuseofmethodnameswhileprovidingspecializedimplementationsforthem.

Whatdothekeywordstaticandconstsignify?

Whenaclassmemberisdeclaredtobeofastatictype,itmeansthatthememberisnotaninstancevariablebutaclassvariable.Suchamemberisaccessedusing(asopposedto.ConstisakeywordusedinC++tospecifythatanobject'svaluecannotbechanged.

Whatisastaticmemberofaclass?

Staticdatamembersexistoncefortheentireclass,asopposedtonon-staticdatamembers,whichexistindividuallyineachinstanceofaclass.

Howdoyouaccessthestaticmemberofaclass?

:

:

.

WhatfeatureofC++wouldyouuseifyouwantedtodesignamemberfunctionthatguaranteestoleavethisobjectunchanged?

Itisconstasin:

intMyFunc?

(inttest)const;

Whatisthedifferencebetweenconstchar*myPointer;andchar*constmyPointer;?

constchar*myPointer;isanon-constantpointertoconstantdata;whilechar*constmyPointer;isaconstantpointertonon-constantdata.

Howismemoryallocated/deallocatedinC?

HowaboutC++?

MemoryisallocatedinCusingmalloc()andfreedusingfree().InC++thenew()operatorisusedtoallocatememorytoanobjectandthedelete()operatorisusedtofreethememorytakenupbyanobject.

Whatisthedifferencebetweenpublic,protected,andprivatemembersofaclass?

Privatemembersareaccessibleonlybymembersandfriendsoftheclass.Protectedmembersareaccessiblebymembersandfriendsoftheclassandbymembersandfriendsofderivedclasses.Publicmembersareaccessiblebyeveryone.

HowdoyoulinkaC++programtoCfunctions?

Byusingtheextern"C"linkagespecificationaroundtheCfunctiondeclarations.

Th

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 表格模板 > 合同协议

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1