为了正常的体验网站,请在浏览器设置里面开启Javascript功能!
首页 > 嵌入式面试问题及解答(英文)

嵌入式面试问题及解答(英文)

2021-06-07 5页 doc 28KB 21阅读

用户头像 个人认证

is_601737

暂无简介

举报
嵌入式面试问题及解答(英文).Basiccquestion.1.Question:whereinmemorythevariablesarestored?Localvariables,globalvariables,static.AnswerLocalvariablessitinStack.GlobalandstaticgotoDatasegment.DynamicmemorycomesfromHeap.2.Questioncanyouexplianthemeaningforthefollwoingprogramchar*c1,*c2,*c3,*c4,*c...
嵌入式面试问题及解答(英文)
.Basiccquestion.1.Question:whereinmemorythevariablesarestored?Localvariables,globalvariables,static.AnswerLocalvariablessitinStack.GlobalandstaticgotoDatasegment.DynamicmemorycomesfromHeap.2.Questioncanyouexplianthemeaningforthefollwoingprogramchar*c1,*c2,*c3,*c4,*c5;charanalysis[8]={'a','n','a','l','y','s','i','s'};intmain(){c5=c4=analysis;++c4;c3=&analysis[6];c2=c5+2;c1=&analysis[7]-3;printf("%c\t%c\t%c\t%c\t%c",*c1,*c2,*c3,*c4,*c5);return0;}Answerc1,c2,c3,c4andc5arepointers(whichcanholdaddresses).analysisisanarrayvariablewhichisholdingthestring"analysis".>c5=c4=analysis;Thestartingaddressofthearrayisgiventoc5andc4.Hencetheypointtofirstcharacter'a'inthearray.>++c4;c4isincrementedby1.Hencepointsto'n'inthearray.>c3=&analysis[6];c3isgiventheaddressof7thcharacter(countfrom0)ofthearray.Hencec3pointstocharacter'i'.>c2=c5+2;..c5pointstofirstcharacter.plus2means,c2pointsto3rdcharacter'a'(second'a'inthestring).>c1=&analysis[7]-3;c1pointsto3rdcharacterfromtheend(notcountingthelastcharacter).c1holdstheaddress.*c1meansthedatastroredatc1.Sincec1pointsto3rdcharacterfromtheend(thatis5thcharacter-countstartsfrom0),*choldscharacter'y'.Hence*c1willprint'y'onthescreen.Similarlyforotherpointervariables*c2,*c3,*c4and*c53.Question:a=5b=10c=7(a>c)?a:((b>c)?b:c)Answer:104Question:HowdoyoudeclareanarrayofNpointerstofunctionsreturningpointerstofunctionsreturningpointerstocharacters?A.char*(*(*a[N])())();B.Buildthedeclarationupincrementally,usingtypedefs:C.Usethecdeclprogram,whichturnsEnglishintoCandviceversa:D.Alloftheabove.Answer:D5Question:voidmain(){intcount=10,*temp,sum=0;temp=&count;*temp=20;temp=∑*temp=count;printf("%d%d%d",count,*temp,sum);}Answer:20;20;20;..6Question:voidmain(){inti=7;printf("%d",i++*i++);}Answer:49.Note:Don’tchangeavariabletwiceinoneexpression.7Question:Thenumberofsyntaxerrorsintheprogram?intf()voidmain(){f(1);f(1,2);f(1,2,3);}f(inti,intj,intk){printf("%d%d%d",i,j,k);}Answer:None.8Question:voidmain(){floatj;j=1000*1000;printf("%f",j);}1000000OverflowErrorNoneoftheaboveAnswer:D..9Question:Givetheoutputoftheprogramvoidmain(){unsignedi=1;/*unsignedchark=-1=>k=255;*/signedj=-1;/*chark=-1=>k=65535*//*unsignedorsignedintk=-1=>k=65535*/if(ij)printf("greater");elseif(i==j)printf("equal");}Answer:less10Givetheoutputoftheprogramvoidmain(){char*s="12345sn";printf("%d",sizeof(s));}Answer:411Question:Givetheoutputoftheprogramvoidmain(){inti;for(i=1;i<4,i++)switch(i)case1:printf("%d",i);break;{case2:printf("%d",i);break;case3:printf("%d",i);break;}..switch(i)case4:printf("%d",i);}Answer:1,2,3,412.Question:HowtopasstwoargumentstoafunctionpromptedtobyfunctionpointerA.g->(1,2)*g(1,2)(*g)(1,2)g(1,2)Answer:C13Question:Canyouhaveconstantvolatilevariable?Answer:YES.Wecanhaveaconstvolatilevariable.avolatilevariableisavariablewhichcanbechangedbytheextrenalevents(likeaninterrputtimerswillincrementthevoltilevarible.Ifyoudontwantyouvolatilevaribaletobechangedthendeclarethemas“constvolatile”.14.Question:studythecode:#includevoidmain(){constinta=100;int*p;p=&a;(*p)++;printf("a=%d\n(*p)=%d\n",a,*p);}Whatisprinted?A)100,101B)100,100C)101,101D)Noneoftheabove..AnswerCEmbeddedCUsingthe#definestatement,howwouldyoudeclareamanifestconstantthatreturnsthenumberofsecondsinayear?Disregardleapyearsinyouranswer.Answer#defineSECONDS_PER_YEAR(60*60*24*365)ULI'mlookingforseveralthingshere:Basicknowledgeofthe#definesyntax(forexample,nosemi-colonattheend,theneedtoparenthesize,andsoon)Anunderstandingthatthepre-processorwillevaluateconstantexpressionsforyou.Thus,itisclearer,andpenalty-free,tospellouthowyouarecalculatingthenumberofsecondsinayear,ratherthanactuallydoingthecalculationyourselfArealizationthattheexpressionwilloverflowanintegerargumentona16-bitmachine-hencetheneedfortheL,tellingthecompilertotreatthevariableasaLongAsabonus,ifyoumodifiedtheexpressionwithaUL(indicatingunsignedlong),thenyouareofftoagreatstart.Andremember,firstimpressionscount!Writethe"standard"MINmacro-thatis,amacrothattakestwoargumentsandreturnsthesmallerofthetwoarguments.Answer:#defineMIN(A,B)((A)<=(B)?(A):(B))Thepurposeofthisquestionistotestthefollowing:Basicknowledgeofthe#definedirectiveasusedinmacros.ThisisimportantbecauseuntiltheinlineoperatorbecomespartofstandardC,macrosaretheonlyportablewayofgeneratinginlinecode.InlinecodeisoftennecessaryinembeddedsystemsinordertoachievetherequiredperformancelevelKnowledgeoftheternaryconditionaloperator.ThisoperatorexistsinCbecauseitallowsthecompilertoproducemoreoptimalcodethananif-then-elsesequence.Giventhatperformanceisnormallyanissueinembeddedsystems,knowledgeanduseofthisconstructisimportantUnderstandingoftheneedtoverycarefullyparenthesizeargumentstomacrosIalsousethisquestiontostartadiscussiononthesideeffectsofmacros,forexample,whathappenswhenyouwritecodesuchas:..least=MIN(*p++,b);Infiniteloopsoftenariseinembeddedsystems.HowdoesyoucodeaninfiniteloopinC?Thereareseveralsolutionstothisquestion.Mypreferredsolutionis:Answer:while(1){?}Usingthevariablea,givedefinitionsforthefollowing:a)AnintegerApointertoanintegerApointertoapointertoanintegerAnarrayof10integersAnarrayof10pointerstointegersApointertoanarrayof10integersApointertoafunctionthattakesanintegerasanargumentandreturnsanintegerAnarrayoftenpointerstofunctionsthattakeanintegerargumentandreturnanintegerAnswers:inta;//Anintegerint*a;//Apointertoanintegerint**a;//Apointertoapointertoanintegerinta[10];//Anarrayof10integersint*a[10];//Anarrayof10pointerstointegersint(*a)[10];//Apointertoanarrayof10integersint(*a)(int);//Apointertoafunctionathattakesanintegerargumentandreturnsanintegerint(*a[10])(int);//Anarrayof10pointerstofunctionsthattakeanintegerargumentandreturnanintegerPeopleoftenclaimthatacoupleofthesearethesortsofthingthatonelooksupintextbooks-andIagree.Whilewritingthisarticle,Iconsultedtextbookstoensurethesyntaxwascorrect.However,Iexpecttobeaskedthisquestion(orsomethingclosetoit)whenI'mbeinginterviewed.Consequently,ImakesureIknowtheanswers,atleastforthefewhoursoftheinterview.Candidateswhodon'tknowalltheanswers(oratleastmostofthem)aresimplyunpreparedfortheinterview.Iftheycan'tbepreparedfortheinterview,whatwilltheybepreparedfor?..6.Whataretheusesofthekeywordstatic?Answer:StatichasthreedistinctusesinC:AvariabledeclaredstaticwithinthebodyofafunctionmaintainsitsvaluebetweenfunctioninvocationsAvariabledeclaredstaticwithinamodule,(butoutsidethebodyofafunction)isaccessiblebyallfunctionswithinthatmodule.Itisnotaccessiblebyfunctionswithinanyothermodule.Thatis,itisalocalizedglobalFunctionsdeclaredstaticwithinamodulemayonlybecalledbyotherfunctionswithinthatmodule.Thatis,thescopeofthefunctionislocalizedtothemodulewithinwhichitisdeclaredMostcandidatesgetthefirstpartcorrect.Areasonablenumbergetthesecondpartcorrect,whileapitifulnumberunderstandthethirdanswer.Thisisaseriousweaknessinacandidate,sinceheobviouslydoesn'tunderstandtheimportanceandbenefitsoflocalizingthescopeofbothdataandcode.7.Whatdothefollowingdeclarationsmean?constinta;intconsta;constint*a;int*consta;intconst*consta;AnswerThefirsttwomeanthesamething,namelyaisaconst(read-only)integer.Thethirdmeansaisapointertoaconstinteger(thatis,theintegerisn'tmodifiable,butthepointeris).Thefourthdeclaresatobeaconstpointertoaninteger(thatis,theintegerpointedtobyaismodifiable,butthepointerisnot).Thefinaldeclarationdeclaresatobeaconstpointertoaconstinteger(thatis,neithertheintegerpointedtobya,northepointeritselfmaybemodified).8.Whatdoesthekeywordvolatilemean?Givethreedifferentexamplesofitsuse.Answer:Avolatilevariableisonethatcanchangeunexpectedly.Consequently,thecompilercanmakenoassumptionsaboutthevalueofthevariable.Inparticular,theoptimizermustbecarefultoreloadthevariableeverytimeitisusedinsteadofholdingacopyinaregister.Examplesofvolatilevariablesare:..Hardwareregistersinperipherals(forexample,statusregisters)Non-automaticvariablesreferencedwithinaninterruptserviceroutineVariablessharedbymultipletasksinamulti-threadedapplication9.Canapointerbevolatile?Explain.Yes,althoughthisisnotverycommon.Anexampleiswhenaninterruptserviceroutinemodifiesapointertoabuffer10.What'swrongwiththefollowingfunction?:intsquare(volatileint*ptr){return*ptr**ptr;}Answers:Thisoneiswicked.Theintentofthecodeistoreturnthesquareofthevaluepointedtoby*ptr.However,since*ptrpointstoavolatileparameter,thecompilerwillgeneratecodethatlookssomethinglikethis:intsquare(volatileint*ptr){inta,b;a=*ptr;b=*ptr;returna*b;}Becauseit'spossibleforthevalueof*ptrtochangeunexpectedly,itispossibleforaandbtobedifferent.Consequently,thiscodecouldreturnanumberthatisnotasquare!Thecorrectwaytocodethisis:longsquare(volatileint*ptr){inta;a=*ptr;returna*a;}..11.Embeddedsystemsalwaysrequiretheusertomanipulatebitsinregistersorvariables.Givenanintegervariablea,writetwocodefragments.Thefirstshouldsetbit3ofa.Thesecondshouldclearbit3ofa.Inbothcases,theremainingbitsshouldbeunmodified.Answer:Use#definesandbitmasks.Thisisahighlyportablemethodandistheonethatshouldbeused.Myoptimalsolutiontothisproblemwouldbe:#defineBIT3(0x1<<3)staticinta;voidset_bit3(void){a|=BIT3;}voidclear_bit3(void){a&=~BIT3;}12Embeddedsystemsareoftencharacterizedbyrequiringtheprogrammertoaccessaspecificmemorylocation.Onacertainprojectitisrequiredtosetanintegervariableattheabsoluteaddress0x67a9tothevalue0xaa55.ThecompilerisapureANSIcompiler.Writecodetoaccomplishthistask.Answer:int*ptr;ptr=(int*)0x67a9;*ptr=0xaa55;Whatdoesthefollowingcodeoutputandwhy?voidfoo(void){unsignedinta=6;intb=-20;(a+b>6)?puts(">6"):puts("<=6");}Theansweristhatthisoutputs">6."Thereasonforthisisthatexpressionsinvolvingsignedandunsignedtypeshavealloperandspromotedtounsignedtypes.Thus?0becomesaverylarge..positiveintegerandtheexpressionevaluatestogreaterthan6.Thisisaveryimportantpointinembeddedsystemswhereunsigneddatatypesshouldbeusedfrequently.14.Whatdoesthefollowingcodefragmentoutputandwhy?char*ptr;if((ptr=(char*)malloc(0))==NULL)puts("Gotanullpointer");elseputs("Gotavalidpointer");Answer:GotavalidpointerThisisafunquestion.Istumbledacrossthisonlyrecentlywhenacolleagueofmineinadvertentlypassedavalueof0tomallocandgotbackavalidpointer!Thatis,theabovecodewilloutput"Gotavalidpointer."Iusethistostartadiscussiononwhethertheintervieweethinksthisisthecorrectthingforthelibraryroutinetodo.Gettingtherightanswerhereisnotnearlyasimportantasthewayyouapproachtheproblemandtherationaleforyourdecision.15.TypedefisfrequentlyusedinCtodeclaresynonymsforpre-existingdatatypes.Itisalsopossibletousethepreprocessortodosomethingsimilar.Forinstance,considerthefollowingcodefragment:#definedPSstructs*typedefstructs*tPS;TheintentinbothcasesistodefinedPSandtPStobepointerstostructures.Whichmethod,ifany,ispreferredandwhy?Theansweristhetypedefispreferred.Considerthedeclarations:dPSp1,p2;tPSp3,p4;Thefirstexpandsto:structs*p1,p2;whichdefinesp1tobeapointertothestructureandp2tobeanactualstructure,whichisprobablynotwhatyouwanted.Thesecondexamplecorrectlydefinesp3andp4tobepointers.Obscuresyntax16.Callowssomeappallingconstructs.Isthisconstructlegal,andifsowhatdoesthiscodedo?..inta=5,b=7,c;c=a+++b;Thiscodeistreatedas:c=a+++b;Thus,afterthiscodeisexecuted,a=6,b=7,andc=12.Real-timequestion1.Whatisreal-timesystem?"Areal-timesystemisoneinwhichthecorrectnessofthecomputationsnotonlydependsuponthelogicalcorrectnessofthecomputationbutalsouponthetimeatwhichtheresultisproduced.Ifthetimingconstraintsofthesystemarenotmet,systemfailureissaidtohaveoccurred."2.WhatisrealtimeoperatingsystemPOSIXStandard1003.1defines"real-time"foroperatingsystemsas:"Realtimeinoperatingsystems:theabilityoftheoperatingsystemtoprovidearequiredlevelofserviceinaboundedresponsetime"3.Whatisracecondition?Raceconditionisanundesirablesituationthatoccurswhentwotasksupdateshareddatasimultaneously;difficulttocatch;theoperationsmustbedoneinthepropersequenceinordertobedonecorrectly.4.Whatiscriticalregion?Criticalregioniswherevertwoormoreprocessesmaymodifythesameresource.Sincemodificationrequiresaccess,overlappingprocesseswouldreceiveincorrectinformationandmayleavetheresourceinaninconsistentstate.Severaloptionsexisttoguaranteeoneactiveprocesstoaregion,semaphoresarethemostprimitive.Whichevermethodisusedthefollowingshouldbeguaranteed:mutualexclusionofprocesses,guaranteedexitforallenteringprocesses,fairschedulingofallprocesses,andanyhigherordersynchronization.5.Whatisdeadlock?Deadlockoccurswhentwoormorethreadsarewaitingonaconditionthatcannotbesatisfied.Deadlockmostoftenoccurswhentwo(ormore)threadsareeachwaitingfortheother(s)todosomething....
/
本文档为【嵌入式面试问题及解答(英文)】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索