Вы находитесь на странице: 1из 16

http://TechPreparaton.

com
2008
C Intervew Ouestons
And Answers
V s t T e c h P r e p a r a t o n . c o m f o r mo r e n t e r v e w q u e s t o n s a n d
a n s w e r s
C lnterview uestions and Answers
What is C language?
The C programmng anguage s a standardzed programmng anguage
deveoped n the eary 1970s by Ken Thompson and Denns Rtche for
use on the UNIX operatng system. It has snce spread to many other
operatng systems, and s one of the most wdey used programmng
anguages. C s przed for ts effcency, and s the most popuar
programmng anguage for wrtng system software, though t s aso
used for wrtng appcatons.
printf() Function
What is the output of printf("%d")?
1. When we wrte prntf("%d",x); ths means comper w prnt the
vaue of x. But as here, there s nothng after %d so comper w show
n output wndow garbage vaue.
2. When we use %d the comper nternay uses t to access the
argument n the stack (argument stack). Ideay comper determnes
the offset of the data varabe dependng on the format specfcaton
strng. Now when we wrte prntf("%d",a) then comper frst accesses
the top most eement n the argument stack of the prntf whch s %d
and dependng on the format strng t cacuated to offset to the actua
data varabe n the memory whch s to be prnted. Now when ony %d
w be present n the prntf then comper w cacuate the correct
offset (whch w be the offset to access the nteger varabe) but as
the actua data ob|ect s to be prnted s not present at that memory
ocaton so t w prnt what ever w be the contents of that memory
ocaton.
3. Some compers check the format strng and w generate an error
wthout the proper number and type of arguments for thngs ke
prntf(...) and scanf(...).
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 2
malloc() Function- What is the difference between "calloc(...)" and
"malloc(...)"?
1. caoc(...) aocates a bock of memory for an array of eements of a
certan sze. By defaut the bock s ntazed to 0. The tota number of
memory aocated w be (number_of_eements * sze).
maoc(...) takes n ony a snge argument whch s the memory
requred n bytes. maoc(...) aocated bytes of memory and not bocks
of memory ke caoc(...).
2. maoc(...) aocates memory bocks and returns a vod ponter to the
aocated space, or NULL f there s nsuffcent memory avaabe.
caoc(...) aocates an array n memory wth eements ntazed to 0
and returns a ponter to the aocated space. caoc(...) cas maoc(...)
n order to use the C++ _set_new_mode functon to set the new
hander mode.
printf() Function- What is the difference between "printf(...)" and
"sprintf(...)"?
srinif(...} wriics daia io iIc cIaracicr array wIcrcas rinif(...} wriics daia io iIc
siandard ouiui dcvicc.
Compilation How to reduce a final size of executable?
Sze of the fna executabe can be reduced usng dynamc nkng for
brares.
Linked Lists -- Can you tell me how to check whether a linked list is circular?
Create two ponters, and set both to the start of the st. Update each
as foows:
whe (ponter1) {
ponter1 = ponter1->next;
ponter2 = ponter2->next;
f (ponter2) ponter2=ponter2->next;
f (ponter1 == ponter2) {
prnt ("crcuar");
}
}
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 3
If a st s crcuar, at some pont ponter2 w wrap around and be
ether at the tem |ust before ponter1, or the tem before that. Ether
way, ts ether 1 or 2 |umps unt they meet.
"union" Data Type What is the output of the following program? Why?
#ncude
man() {
typedef unon {
nt a;
char b|10|;
foat c;
}
Unon;
Unon x,y = {100};
x.a = 50;
strcpy(x.b,"heo");
x.c = 21.50;
prntf("Unon x : %d %s %f n",x.a,x.b,x.c);
prntf("Unon y : %d %s %f n",y.a,y.b,y.c);
}
What does static variable mean?

there are 3 man uses for the statc.


1. If you decare wthn a functon:
It retans the vaue between functon cas
2.If t s decared for a functon name:
By defaut functon s extern..so t w be vsbe from other fes f the
functon decaraton s as statc..t s nvsbe for the outer fes
3. Statc for goba varabes:
By defaut we can use the goba varabes from outsde fes If t s
statc goba..that varabe s mted to wth n the fe
Advantages of a macro over a function?
Macro gets to see the Compaton envronment, so t can expand __
__TIME__ __FILE__ #defnes. It s expanded by the preprocessor.
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 4
For exampe, you cant do ths wthout macros
#defne PRINT(EXPR) prntf( #EXPR "=%d\n", EXPR)
PRINT( 5+6*7 ) // expands nto prntf("5+6*7=%d", 5+6*7 );
You can defne your mn anguage wth macros:
#defne strequa(A,B) (!strcmp(A,B))
Macros are a necessary evs of fe. The pursts dont ke them, but
wthout t no rea work gets done.
What are the differences between malloc() and calloc()?
There are 2 dfferences.
Frst, s n the number of arguments. maoc() takes a snge
argument(memory requred n bytes), whe caoc() needs 2
arguments(number of varabes to aocate memory, sze n bytes of a
snge varabe).
Secondy, maoc() does not ntaze the memory aocated, whe
caoc() ntazes the aocated memory to ZERO.
What are the different storage classes in C?
C has three types of storage: automatc, statc and aocated.
Varabe havng bock scope and wthout statc specfer have
automatc storage duraton.
Varabes wth bock scope, and wth statc specfer have statc scope.
Goba varabes (.e, fe scope) wth or wthout the statc specfer aso
have statc scope.
Memory obtaned from cas to maoc(), aoc() or reaoc() beongs to
aocated storage cass.
What is the difference between strings and character arrays?
A ma|or dfference s: strng w have statc storage duraton, whereas
as a character array w not, uness t s expcty specfed by usng the
statc keyword.
Actuay, a strng s a character array wth foowng propertes:
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 5
* the mutbyte character sequence, to whch we generay ca strng,
s used to ntaze an array of statc storage duraton. The sze of ths
array s |ust suffcent to contan these characters pus the termnatng
NUL character.
* t not specfed what happens f ths array, .e., strng, s modfed.
* Two strngs of same vaue|1| may share same memory area. For
exampe, n the foowng decaratons:
char *s1 = "Cavn and Hobbes";
char *s2 = "Cavn and Hobbes";
the strngs ponted by s1 and s2 may resde n the same memory
ocaton. But, t s not true for the foowng:
char ca1|| = "Cavn and Hobbes";
char ca2|| = "Cavn and Hobbes";
|1| The vaue of a strng s the sequence of the vaues of the contaned
characters, n order.
Difference between const char* p and char const* p
In const char* p, the character ponted by p s constant, so u cant
change the vaue of character ponted by p but u can make p refer to
some other ocaton.
n char const* p, the ptr p s constant not the character referenced by
t, so u cant make p to reference to any other ocaton but u can
change the vaue of the char ponted by p.
What is hashing?
To hash means to grnd up, and thats essentay what hashng s a
about. The heart of a hashng agorthm s a hash functon that takes
your nce, neat data and grnds t nto some random-ookng nteger.
The dea behnd hashng s that some data ether has no nherent
orderng (such as mages) or s expensve to compare (such as
mages). If the data has no nherent orderng, you cant perform
comparson searches.
If the data s expensve to compare, the number of comparsons used
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 6
even by a bnary search mght be too many. So nstead of ookng at
the data themseves, you condense (hash) the data to an nteger (ts
hash vaue) and keep a the data wth the same hash vaue n the
same pace. Ths task s carred out by usng the hash vaue as an
ndex nto an array.
To search for an tem, you smpy hash t and ook at a the data whose
hash vaues match that of the data youre ookng for. Ths technque
greaty essens the number of tems you have to ook at. If the
parameters are set up wth care and enough storage s avaabe for
the hash tabe, the number of comparsons needed to fnd an tem can
be made arbtrary cose to one.
One aspect that affects the effcency of a hashng mpementaton s
the hash functon tsef. It shoud deay dstrbute data randomy
throughout the entre hash tabe, to reduce the kehood of cosons.
Cosons occur when two dfferent keys have the same hash vaue.
There are two ways to resove ths probem. In open addressng, the
coson s resoved by the choosng of another poston n the hash
tabe for the eement nserted ater. When the hash tabe s searched, f
the entry s not found at ts hashed poston n the tabe, the search
contnues checkng unt ether the eement s found or an empty
poston n the tabe s found.
The second method of resovng a hash coson s caed channg. In
ths method, a bucket or nked st hods a the eements whose keys
hash to the same vaue. When the hash tabe s searched, the st must
be searched neary.
How can you determine the size of an allocated portion of memory?
You cant, reay. free() can , but theres no way for your program to
know the trck free() uses. Even f you dsassembe the brary and
dscover the trck, theres no guarantee the trck wont change wth the
next reease of the comper.
Can static variables be declared in a header file?
You cant decare a statc varabe wthout defnng t as we (ths s
because the storage cass modfers statc and extern are mutuay
excusve). A statc varabe can be defned n a header fe, but ths
woud cause each source fe that ncuded the header fe to have ts
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 7
own prvate copy of the varabe, whch s probaby not what was
ntended.
Can a variable be both const and volatile?
Yes. The const modfer means that ths code cannot change the vaue
of the varabe, but that does not mean that the vaue cannot be
changed by means outsde ths code. For nstance, n the exampe n
FAO 8, the tmer structure was accessed through a voate const
ponter. The functon tsef dd not change the vaue of the tmer, so t
was decared const. However, the vaue was changed by hardware on
the computer, so t was decared voate. If a varabe s both const and
voate, the two modfers can appear n ether order.
Can include files be nested?
Yes. Incude fes can be nested any number of tmes. As ong as you
use precautonary measures , you can avod ncudng the same fe
twce. In the past, nestng header fes was seen as bad programmng
practce, because t compcates the dependency trackng functon of
the MAKE program and thus sows down compaton. Many of todays
popuar compers make up for ths dffcuty by mpementng a
concept caed precomped headers, n whch a headers and
assocated dependences are stored n a precomped state.
Many programmers ke to create a custom header fe that has
#ncude statements for every header needed for each modue. Ths s
perfecty acceptabe and can hep avod potenta probems reatng to
#ncude fes, such as accdentay omttng an #ncude fe n a
modue.
When does the compiler not implicitly generate the address of the first
element of an array?
Whenever an array name appears n an expresson such as
- array as an operand of the szeof operator
- array as an operand of & operator
- array as a strng tera ntazer for a character array
Then the comper does not mpcty generate the address of the
address of the frst eement of an array.
What is a null pointer?
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 8
There are tmes when ts necessary to have a ponter that doesnt
pont to anythng. The macro NULL, defned n , has a vaue thats
guaranteed to be dfferent from any vad ponter. NULL s a tera zero,
possby cast to vod* or char*. Some peope, notaby C++
programmers, prefer to use 0 rather than NULL.
The nu ponter s used n three ways:
1) To stop ndrecton n a recursve data structure
2) As an error vaue
3) As a sentne vaue
What is the difference between text and binary modes?
Streams can be cassfed nto two types: text streams and bnary
streams. Text streams are nterpreted, wth a maxmum ength of 255
characters. Wth text streams, carrage return/ne feed combnatons
are transated to the newne n character and vce versa. Bnary
streams are unnterrupted and are treated one byte at a tme wth no
transaton of characters. Typcay, a text stream woud be used for
readng and wrtng standard text fes, prntng output to the screen or
prnter, or recevng nput from the keyboard.
A bnary text stream woud typcay be used for readng and wrtng
bnary fes such as graphcs or word processng documents, readng
mouse nput, or readng and wrtng to the modem.
What is static memory allocation and dynamic memory allocation?
Statc memory aocaton: The comper aocates the requred memory
space for a decared varabe.By usng the address of operator,the
reserved address s obtaned and ths address may be assgned to a
ponter varabe.Snce most of the decared varabe have statc
memory,ths way of assgnng ponter vaue to a ponter varabe s
known as statc memory aocaton. memory s assgned durng
compaton tme.
Dynamc memory aocaton: It uses functons such as maoc( ) or
caoc( ) to get memory dynamcay.If these functons are used to get
memory dynamcay and the vaues returned by these functons are
assngned to ponter varabes, such assgnments are known as
dynamc memory aocaton.memory s assned durng run tme.
When should a far pointer be used?
Sometmes you can get away wth usng a sma memory mode n
most of a gven program. There mght be |ust a few thngs that dont ft
n your sma data and code segments. When that happens, you can
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 9
use expct far ponters and functon decaratons to get at the rest of
memory. A far functon can be outsde the 64KB segment most
functons are shoehorned nto for a sma-code mode. (Often, brares
are decared expcty far, so they work no matter what code mode
the program uses.) A far ponter can refer to nformaton outsde the
64KB data segment. Typcay, such ponters are used wth farmaoc()
and such, to manage a heap separate from where a the rest of the
data ves. If you use a sma-data, arge-code mode, you shoud
expcty make your functon ponters far.
How are pointer variables initialized?
Ponter varabe are ntazed by one of the foowng two ways
- Statc memory aocaton
- Dynamc memory aocaton
Difference between arrays and pointers?
- Ponters are used to manpuate data usng the address. Ponters use
* operator to access the data ponted to by them
- Arrays use subscrpted varabes to access and manpuate data.
Array varabes can be equvaenty wrtten usng ponter expresson.
Is using exit() the same as using return?
No. The ext() functon s used to ext your program and return contro
to the operatng system. The return statement s used to return from a
functon and return contro to the cang functon. If you ssue a return
from the man() functon, you are essentay returnng contro to the
cang functon, whch s the operatng system. In ths case, the return
statement and ext() functon are smar.
What is a method?
Method s a way of dong somethng, especay a systematc way;
mpes an ordery ogca arrangement (usuay n steps).
What is indirection?
If you decare a varabe, ts name s a drect reference to ts vaue. If
you have a ponter to a varabe, or any other ob|ect n memory, you
have an ndrect reference to ts vaue.
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 10
What is modular programming?
If a program s arge, t s subdvded nto a number of smaer
programs that are caed modues or subprograms. If a compex
probem s soved usng more modues, ths approach s known as
moduar programmng.
How many levels deep can include files be nested?
Even though there s no mt to the number of eves of nested ncude
fes you can have, your comper mght run out of stack space whe
tryng to ncude an nordnatey hgh number of fes. Ths number
vares accordng to your hardware confguraton and possby your
comper.
What is the difference between declaring a variable and defining a variable?

Decarng a varabe means descrbng ts type to the comper but not


aocatng any space for t. Defnng a varabe means decarng t and
aso aocatng space to hod the varabe. You can aso ntaze a
varabe at the tme t s defned.
What is an lvalue?
An vaue s an expresson to whch a vaue can be assgned. The vaue
expresson s ocated on the eft sde of an assgnment statement,
whereas an rvaue s ocated on the rght sde of an assgnment
statement. Each assgnment statement must have an vaue and an
rvaue. The vaue expresson must reference a storabe varabe n
memory. It cannot be a constant.
Differentiate between an internal static and external static variable?
An nterna statc varabe s decared nsde a bock wth statc storage
cass whereas an externa statc varabe s decared outsde a the
bocks n a fe.An nterna statc varabe has persstent storage,bock
scope and no nkage.An externa statc varabe has permanent
storage,fe scope and nterna nkage.
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 11
What is the difference between a string and an array?
An array s an array of anythng. A strng s a specfc knd of an array
wth a we-known conventon to determne ts ength.
There are two knds of programmng anguages: those n whch a strng
s |ust an array of characters, and those n whch ts a speca type. In
C, a strng s |ust an array of characters (type char), wth one wrnke: a
C strng aways ends wth a NUL character.
The "vaue" of an array s the same as the address of (or a ponter to)
the frst eement; so, frequenty, a C strng and a ponter to char are
used to mean the same thng.
An array can be any ength. If ts passed to a functon, theres no way
the functon can te how ong the array s supposed to be, uness some
conventon s used. The conventon for strngs s NUL termnaton; the
ast character s an ASCII NUL () character.
What is an argument? Differentiate between formal arguments and actual
arguments?
An argument s an entty used to pass the data from cang functon to
the caed functon. Forma arguments are the arguments avaabe n
the functon defnton. They are preceded by ther own data types.
Actua arguments are avaabe n the functon ca.
What are advantages and disadvantages of external storage class?
Advantages of externa storage cass
1)Persstent storage of a varabe retans the atest vaue
2)The vaue s gobay avaabe
Dsadvantages of externa storage cass
1)The storage for an externa varabe exsts even when the varabe s
not needed
2)The sde effect may produce surprsng output
3)Modfcaton of the program s dffcut
4)Generaty of a program s affected
What is a void pointer?
A vod ponter s a C conventon for a raw address. The comper has no
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 12
dea what type of ob|ect a vod Ponter reay ponts to. If you wrte
nt *p;
p ponts to an nt. If you wrte
vod *p;
p doesnt pont to a vod!
In C and C++, any tme you need a vod ponter, you can use another
ponter type. For exampe, f you have a char*, you can pass t to a
functon that expects a vod*. You dont even need to cast t. In C (but
not n C++), you can use a vod* any tme you need any knd of
ponter, wthout castng. (In C++, you need to cast t).
A vod ponter s used for workng wth raw memory or for passng a
ponter to an unspecfed type.
Some C code operates on raw memory. When C was frst nvented,
character ponters (char *) were used for that. Then peope started
gettng confused about when a character ponter was a strng, when t
was a character array, and when t was raw memory.
When should a type cast not be used?
A type cast shoud not be used to overrde a const or voate
decaraton. Overrdng these type modfers can cause the program to
fa to run correcty.
A type cast shoud not be used to turn a ponter to one type of
structure or data type nto another. In the rare events n whch ths
acton s benefca, usng a unon to hod the vaues makes the
programmers ntentons cearer.
When is a switch statement better than multiple if statements?
A swtch statement s generay best to use when you have more than
two condtona expressons based on a snge varabe of numerc type.
What is a static function?
A statc functon s a functon whose scope s mted to the current
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 13
source fe. Scope refers to the vsbty of a functon or varabe. If the
functon or varabe s vsbe outsde of the current source fe, t s sad
to have goba, or externa, scope. If the functon or varabe s not
vsbe outsde of the current source fe, t s sad to have oca, or
statc, scope.
What is a pointer variable?
A ponter varabe s a varabe that may contan the address of another
varabe or any vad address n the memory.
What is a pointer value and address?
A ponter vaue s a data ob|ect that refers to a memory ocaton. Each
memory ocaton s numbered n the memory. The number attached to
a memory ocaton s caed the address of the ocaton.
What is a modulus operator? What are the restrictions of a modulus
operator?
A Moduus operator gves the remander vaue. The resut of x%y s
obtaned by (x-(x/y)*y). Ths operator s apped ony to ntegra
operands and cannot be apped to foat or doube.
Differentiate between a linker and linkage?
A nker converts an ob|ect code nto an executabe code by nkng
together the necessary bud n functons. The form and pace of
decaraton where the varabe s decared n a program determne the
nkage of varabe.
What is a function and built-in function?
A arge program s subdvded nto a number of smaer programs or
subprograms. Each subprogram specfes one or more actons to be
performed for a arge program. such subprograms are functons.
The functon supports ony statc and extern storage casses. By
defaut, functon assumes extern storage cass. functons have goba
scope. Ony regster or auto storage cass s aowed n the functon
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 14
parameters. But-n functons that predefned and supped aong wth
the comper are known as but-n functons. They are aso known as
brary functons.
Why should I prototype a function?
A functon prototype tes the comper what knd of arguments a
functon s ookng to receve and what knd of return vaue a functon
s gong to gve back. Ths approach heps the comper ensure that
cas to a functon are made correcty and that no erroneous type
conversons are takng pace.
What is Polymorphism ?
'Poymorphsm' s an ob|ect orented term. Poymorphsm may be
defned as the abty of reated ob|ects to respond to the same
message wth dfferent, but approprate actons. In other words,
poymorphsm means takng more than one form. Poymorphsm eads
to two mportant aspects n Ob|ect Orented termnoogy - Functon
Overoadng and Functon Overrdng. Overoadng s the practce of
suppyng more than one defnton for a gven functon name n the
same scope. The comper s eft to pck the approprate verson of the
functon or operator based on the arguments wth whch t s caed.
Overrdng refers to the modfcatons made n the sub cass to the
nherted methods from the base cass to change ther behavor.
What is Operator overloading ?
When an operator s overoaded, t takes on an addtona meanng
reatve to a certan cass. But t can st retan a of ts od meanngs.
Exampes:
1) The operators >> and << may be used for I/O operatons because
n the header, they are overoaded.
2) In a stack cass t s possbe to overoad the + operator so that t
appends the contents of one stack to the contents of another. But the
+ operator st retans ts orgna meanng reatve to other types of
data.
What is the difference between goto and longjmp() and setjmp()?
A goto statement mpements a oca |ump of program executon, and
the ong|mp() and set|mp() functons mpement a nonoca, or far,
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 15
|ump of program executon.
Generay, a |ump n executon of any knd shoud be avoded because
t s not consdered good programmng practce to use such statements
as goto and ong|mp n your program.
A goto statement smpy bypasses code n your program and |umps to
a predefned poston. To use the goto statement, you gve t a abeed
poston to |ump to. Ths predefned poston must be wthn the same
functon. You cannot mpement gotos between functons.
When your program cas set|mp(), the current state of your program s
saved n a structure of type |mp_buf. Later, your program can ca the
ong|mp() functon to restore the programs state as t was when you
caed set|mp().Unke the goto statement, the ong|mp() and set|mp()
functons do not need to be mpemented n the same functon.
However, there s a ma|or drawback to usng these functons: your
program, when restored to ts prevousy saved state, w ose ts
references to any dynamcay aocated memory between the
ong|mp() and the set|mp(). Ths means you w waste memory for
every maoc() or caoc() you have mpemented between your
ong|mp() and set|mp(), and your program w be horrby neffcent.
It s hghy recommended that you avod usng functons such as
ong|mp() and set|mp() because they, ke the goto statement, are
qute often an ndcaton of poor programmng practce.
Vst http://TechPreparaton.com for more Intervew Ouestons wth Answers Page 16

Вам также может понравиться