Sei sulla pagina 1di 43

Next Blog» Create Blog | Sign In

c faqs

Thursday, May 31, 2007 Make A Donation

Download Free 320kbps Songs


Free 320kbps Hindi And Telugu Songs Download

Earn Money Through SMS Home

Sign Up Here Home

Posted by prashanth at 12:12 PM 0 comments


More C/C++ faqs Click Here

More C/C++ faqs Click Here

Tuesday, May 29, 2007 C/C++ Ebooks Click HERE


c faqs C/C++ Ebooks Click HERE

1) List object oriented methodologies


2) Name some object oriented languages Labels
3) What are the features of object oriented language C/C++ Faqs Collection 1 (1)
4) What is method overloading
5) What is method overriding Faqs 1 (1)
6) When would one define a static variable / global variable ?
Faqs 2 (1)
Difference between them?
7) What is Default constructor? Important C Questions With
8) What is Copy constructor? answers (1)
9) What is Conversion constructor?
10) Difference between method and message?
11) Difference between C++ Struct and C++ class? Blog Archive
12) What is an abstract class?
13) What is pure virtual class? ▼ 2007 (5)
14) What do you understand by namescape?
▼ May (5)
15) What is Virtual Destructor?
16) What is the diff between "new" and "operator new" ? Download Free 320kbps
17) What is operator overloading? What operators can be overloaded? Songs Free 320kbps
18) What does static variable mean? Hindi An...
19) What is static identifier?
20) What is a pointer? c faqs
21) What is a reference?
faqs 2
22) Difference between pointer and reference?
23) What is a structure? Important C Questions
24) What are the differences between structures and arrays? With answers
25) What is difference between pass by value and pass by reference?
26) What are the differences between malloc() and calloc()? C/C++ Faqs Collection 1
27) What are macros?
28) What are the advantages and disadvantages of macros?
29) What are templates?
30) Difference between template and macros? About Me
31) Difference between arrays and linked list? PRASHANTH
32) What are enumerations?
View my complete profile
Posted by prashanth at 6:26 AM 0 comments

Labels: Faqs 1
faqs 2

C,C++ Interview Questions Part 1

How do you find out if a linked-list has an end? (i.e. the list is not
a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each
time. The second one goes at 1 nodes each time. If there is a cycle,
the one that goes 2 nodes each time will eventually meet the one
that goes slower. If that is the case, then you will know the linked-
list is a cycle.

What is the difference between realloc() and free()?

The free subroutine frees a block of memory previously allocated by


the malloc subroutine. Undefined results occur if the Pointer
parameter is not a valid pointer. If the Pointer parameter is a null
value, no action will occur. The realloc subroutine changes the size
of the block of memory pointed to by the Pointer parameter to the
number of bytes specified by the Size parameter and returns a new
pointer to the block. The pointer specified by the Pointer parameter
must have been created with the malloc, calloc, or realloc
subroutines and not been deallocated with the free or realloc
subroutines. Undefined results occur if the Pointer parameter is not a
valid pointer.

What is function overloading and operator overloading?

Function overloading: C++ enables several functions of the same


name to be defined, as long as these functions have different sets of
parameters (at least as far as their types are concerned). This
capability is called function overloading. When an overloaded function
is called, the C++ compiler selects the proper function by examining
the number, types and order of the arguments in the call. Function
overloading is commonly used to create several functions of the same
name that perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so


that they work on objects of user-defined classes. Overloaded
operators are syntactic sugar for equivalent function calls. They form
a pleasant facade that doesn't add anything fundamental to the
language (but they can improve understandability and reduce
maintenance costs).

What is the difference between declaration and definition?

The declaration tells the compiler that at some later point we plan to
present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j > =0; j--) //function body
cout << *; cout <<>

What are the advantages of inheritance?

It permits code reusability. Reusability saves time in program


development. It encourages the reuse of proven and debugged high-
quality software, thus reducing problem after a system becomes
functional.
How do you write a function that can reverse a linked-list?

void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;

for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}

What do you mean by inline function?

The idea behind inline functions is to insert the code of a called


function at the point where the function is called. If done carefully,
this can improve the application's performance in exchange for
increased compile time and possibly (but not always) an increase in
the size of the generated binary executables.

Write a program that ask for user input from 5 to 9 then


calculate the average

#include "iostream.h"
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; icout << "Please enter your input between 5 and 9: "; cin
>> numb;
while ( numb<5>9) {
cout << "Invalid input, please re-enter: "; cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " <<>return 0;
}

What is public, protected, private?

● Public, protected and private are three access specifiers in C++.


● Public data members and member functions are accessible
outside the class.
● Protected data members and member functions are only
available to derived classes.
● Private data members and member functions can’t be accessed
outside the class. However there is an exception can be using
friend classes.

Write a function that swaps the values of two integers, using


int* as the argument type.
void swap(int* a, int*b) {
int t;
t = *a;
*a = *b;
*b = t;
}

Tell how to check whether a linked list is circular.

Create two pointers, each set to the start of the list. Update each
as follows:
while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}

OK, why does this work?


If a list is circular, at some point pointer2 will wrap around and be
either at the item just before pointer1, or the item before that. Either
way, it’s either 1 or 2 jumps until they meet.

What is polymorphism?

Polymorphism is the idea that a base class can be inherited by


several classes. A base class pointer can point to its child class and
a base class array can store different child class objects.

What is virtual constructors/destructors?

Answer1
Virtual destructors:
If an object (with a non-virtual destructor) is destroyed explicitly by
applying the delete operator to a base-class pointer to the object,
the base-class destructor function (matching the pointer type) is
called on the object.
There is a simple solution to this problem declare a virtual base-class
destructor.
This makes all derived-class destructors virtual even though they
don’t have the same name as the base-class destructor. Now, if the
object in the hierarchy is destroyed explicitly by applying the delete
operator to a base-class pointer to a derived-class object, the
destructor for the appropriate class is called. Virtual constructor:
Constructors cannot be virtual. Declaring a constructor as a virtual
function is a syntax error.

Answer2
Virtual destructors: If an object (with a non-virtual destructor) is
destroyed explicitly by applying the delete operator to a base-class
pointer to the object, the base-class destructor function (matching
the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-
class destructor. This makes all derived-class destructors virtual
even though they don’t have the same name as the base-class
destructor. Now, if the object in the hierarchy is destroyed explicitly
by applying the delete operator to a base-class pointer to a derived-
class object, the destructor for the appropriate class is called.

Virtual constructor: Constructors cannot be virtual. Declaring a


constructor as a virtual function is a syntax error.

Does c++ support multilevel and multiple inheritance?


Yes.

What are the advantages of inheritance?


• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged high-quality
software, thus reducing problem after a system becomes functional.
What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to
present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j--) //function body
cout<<”*”; cout< What is the difference between an ARRAY and
a LIST?

Answer1
Array is collection of homogeneous elements.
List is collection of heterogeneous elements.

For Array memory allocated is static and continuous.


For List memory allocated is dynamic and Random.

Array: User need not have to keep in track of next memory


allocation.
List: User has to keep in Track of next location where memory is
allocated.

Answer2
Array uses direct access of stored members, list uses sequencial
access for members.

//With Array you have direct access to memory position 5


Object x = a[5]; // x takes directly a reference to 5th element of
array

//With the list you have to cross all previous nodes in order to get
the 5th node:
list mylist;
list::iterator it;

for( it = list.begin() ; it != list.end() ; it++ )


{
if( i==5)
{
x = *it;
break;
}
i++;
}

What is a template?

Templates allow to create generic functions that admit any data type
as parameters and return value without having to overload the
function with all the possible data types. Until certain point they fulfill
the functionality of a macro. Its prototype is any of the two following
ones:

template function_declaration; template function_declaration;

The only difference between both prototypes is the use of keyword


class or typename, its use is indistinct since both expressions have
exactly the same meaning and behave exactly the same way.

You have two pairs: new() and delete() and another pair : alloc
() and free(). Explain differences between eg. new() and malloc
()

Answer1
1.) “new and delete” are preprocessors while “malloc() and free()”
are functions. [we dont use brackets will calling new or delete].
2.) no need of allocate the memory while using “new” but in “malloc
()” we have to use “sizeof()”.
3.) “new” will initlize the new memory to 0 but “malloc()” gives
random value in the new alloted memory location [better to use calloc
()]

Answer2
new() allocates continous space for the object instace
malloc() allocates distributed space.
new() is castless, meaning that allocates memory for this specific
type,
malloc(), calloc() allocate space for void * that is cated to the
specific class type pointer.

What is the difference between class and structure?

Structure: Initially (in C) a structure was used to bundle different


type of data types together to perform a particular functionality. But
C++ extended the structure to contain functions also. The major
difference is that all declarations inside a structure are by default
public.
Class: Class is a successor of Structure. By default all the members
inside the class are private.

What is RTTI?

Runtime type identification (RTTI) lets you find the dynamic type of
an object when you have only a pointer or a reference to the base
type. RTTI is the official way in standard C++ to discover the type of
an object and to convert the type of a pointer or reference (that is,
dynamic typing). The need came from practical experience with C++.
RTTI replaces many homegrown versions with a solid, consistent
approach.

What is encapsulation?

Packaging an object’s variables within its methods is called


encapsulation.

Explain term POLIMORPHISM and give an example using eg.


SHAPE object: If I have a base class SHAPE, how would I define
DRAW methods for two objects CIRCLE and SQUARE

Answer1
POLYMORPHISM : A phenomenon which enables an object to react
differently to the same function call.
in C++ it is attained by using a keyword virtual

Example
public class SHAPE
{
public virtual void SHAPE::DRAW()=0;
}
Note here the function DRAW() is pure virtual which means the sub
classes must implement the DRAW() method and SHAPE cannot be
instatiated

public class CIRCLE::public SHAPE


{
public void CIRCLE::DRAW()
{
// TODO drawing circle
}
}
public class SQUARE::public SHAPE
{
public void SQUARE::DRAW()
{
// TODO drawing square
}
}
now from the user class the calls would be like
globally
SHAPE *newShape;

When user action is to draw


public void MENU::OnClickDrawCircle(){
newShape = new CIRCLE();
}

public void MENU::OnClickDrawCircle(){


newShape = new SQUARE();
}

the when user actually draws


public void CANVAS::OnMouseOperations(){
newShape->DRAW();
}

Answer2
class SHAPE{
public virtual Draw() = 0; //abstract class with a pure virtual method
};

class CIRCLE{
public int r;
public virtual Draw() { this->drawCircle(0,0,r); }
};

class SQURE
public int a;
public virtual Draw() { this->drawRectangular(0,0,a,a); }
};

Each object is driven down from SHAPE implementing Draw() function


in its own way.

What is an object?

Object is a software bundle of variables and related methods.


Objects have state and behavior.

How can you tell what shell you are running on UNIX system?

You can do the Echo $RANDOM. It will return a undefined variable if


you are from the C-Shell, just a return prompt if you are from the
Bourne shell, and a 5 digit random numbers if you are from the Korn
shell. You could also do a ps -l and look for the shell with the highest
PID.

Describe PRIVATE, PROTECTED and PUBLIC – the differences and


give examples.

class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};
Point2D MyPoint;
You cannot directly access private data members when they are
declared (implicitly) private:
MyPoint.x = 5; // Compiler will issue a compile ERROR
//Nor yoy can see them:
int x_dim = MyPoint.x; // Compiler will issue a compile ERROR
On the other hand, you can assign and read the public data members:
MyPoint.color = 255; // no problem
int col = MyPoint.color; // no problem
With protected data members you can read them but not write them:
MyPoint.pinned = true; // Compiler will issue a compile ERROR
bool isPinned = MyPoint.pinned; // no problem

What is namespace?

Namespaces allow us to group a set of global classes, objects and/or


functions under a name. To say it somehow, they serve to split the
global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set
of classes, objects and functions that are included within the
namespace. For example:
namespace general { int a, b; } In this case, a and b are normal
variables integrated within the general namespace. In order to
access to these variables from outside the namespace we have to
use the scope operator ::. For example, to access the previous
variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there
is a possibility that a global object or function can have the same
name than another one, causing a redefinition error.

What do you mean by inheritance?

Inheritance is the process of creating new classes, called derived


classes, from existing classes or base classes. The derived class
inherits all the capabilities of the base class, but can add
embellishments and refinements of its own.

What is a COPY CONSTRUCTOR and when is it called?

A copy constructor is a method that accepts an object of the same


class and copies it’s data members to the object on the left part of
assignement:
class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
public Point2D( const Point2D & ) ;
};
Point2D::Point2D( const Point2D & p )
{
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}
main(){
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has
color = 345

What is Boyce Codd Normal form?

A relation schema R is in BCNF with respect to a set F of functional


dependencies if for all functional dependencies in F+ of the form a-
> , where a and b is a subset of R, at least one of the following holds:
* a- > b is a trivial functional dependency (b is a subset of a)
* a is a superkey for schema R

What is virtual class and friend class?

Friend classes are used when two or more classes are designed to
work together and need access to each other's implementation in
ways that the rest of the world shouldn't be allowed to have. In
other words, they help keep private things private. For instance, it
may be desirable for class DatabaseCursor to have more privilege to
the internals of class Database than main() has.

What is the word you will use when defining a function in base
class to allow this function to be a polimorphic function?

virtual

What do you mean by binding of data and functions?

Encapsulation.

What are 2 ways of exporting a function from a DLL?

1.Taking a reference to the function from the DLL instance.


2. Using the DLL ’s Type Library.

Posted by prashanth at 6:16 AM 0 comments

Labels: Faqs 2

Important C Questions With answers

Declarations and Initializations


● What is the difference between char *a and char a[]?
● How can I declare an array with only one element and still
access elements beyond the first element (in a valid fashion)?
● What's the difference between using a typedef or a #define
for a user-defined type?
● Is char a[3] = "abc"; legal?
● What is the difference between enumeration variables and the
preprocessor #defines?

Variables and Data types


● What is the difference between the declaration and the
definition of a variable?
● Do Global variables start out as zero?
● Does C have boolean variable type?
● Where may variables be defined in C?
● To what does the term storage class refer? What are auto,
static, extern, volatile, const classes?
● What does the typedef keyword do?
● What is the difference between constants defined through
#define and the constant keyword?
● What are Trigraph characters?
● How are floating point numbers stored? Whats the IEEE format?
● When should the register modifier be used?
● When should a type cast be used?

Expressions
● Whats short-circuiting in C expressions?
● Whats wrong with the expression a[i]=i++; ? Whats a
sequence point?
● Does the ?: (ternary operator) return a lvalue? How can I
assign a value to the output of the ternary operator?
● Is 5[array] the same as array[5]?
● What are #pragmas?
● What is the difference between if(0 == x) and if(x == 0)?
● Should we use goto or not?
● Is ++i really faster than i = i + 1?
● What do lvalue and rvalue mean?
● What does the term cast refer to? Why is it used?
● What is the difference between a statement and a block?
● Can comments be nested in C?
● What is type checking?
● Why can't you nest structure definitions?
● What is a forward reference?
● What is the difference between the & and && operators and
the | and || operators?
● Is C case sensitive (ie: does C differentiate between upper
and lower case letters)?
● Can goto be used to jump across functions?
● Whats wrong with #define myptr int *?
● What purpose do #if, #else, #elif, #endif, #ifdef, #ifndef
serve?
● Can we use variables inside a switch statement? Can we use
floating point numbers? Can we use expressions?
● What is more efficient? A switch() or an if() else()?
● What is the difference between a deep copy and a shallow
copy?
● What is operator precedence?

Arrays and Pointers


● How to write functions which accept two-dimensional arrays
when the width is not known before hand?
● If a is an array, is a++ valid?
● Is char a[3] = "abc"; legal? What does it mean?
● How can we find out the length of an array dynamically in C?
● What does *p++ do? Does it increment p or the value pointed
by p?
● What is a NULL pointer? How is it different from an unitialized
pointer? How is a NULL pointer defined?
● What is a null pointer assignment error?
● Does an array always get converted to a pointer? What is the
difference between arr and &arr? How does one declare a
pointer to an entire array?
● Is the cast to malloc() required at all?
● What does malloc() , calloc(), realloc(), free() do? What are
the common problems with malloc()? Is there a way to find out
how much memory a pointer was allocated?
● What's the difference between const char *p, char * const p
and const char * const p?
● What is a void pointer? Why can't we perform arithmetic on a
void * pointer?
● What do Segmentation fault, access violation, core dump and
Bus error mean?
● What is the difference between an array of pointers and a
pointer to an array?
● What is a memory leak?
● What are brk() and sbrk() used for? How are they different
from malloc()?
● What is a dangling pointer? What are reference counters with
respect to pointers?
● What do pointers contain?
● Is *(*(p+i)+j) is equivalent to p[i][j]? Is num[i] == i[num] == *
(num + i) == *(i + num)?
● What operations are valid on pointers? When does one get the
Illegal use of pointer in function error?
● What are near, far and huge pointers?
● What is the difference between malloc() and calloc()?
● Why is sizeof() an operator and not a function?
● What is an opaque pointer?
● What are the common causes of pointer bugs?

Functions
● How to declare a pointer to a function?
● Does extern in a function declaration mean anything?
● How can I return multiple values from a function?
● Does C support function overloading?
● What is the purpose of a function prototype?
● What are inline functions?
● How to declare an array of N pointers to functions returning
pointers to functions returning pointers to characters?
● Can we declare a function that can return a pointer to a
function of the same type?
● How can I write a function that takes a variable number of
arguments? What are the limitations with this? What is vprintf
()?
● With respect to function parameter passing, what is the
difference between call-by-value and call-by-reference?
Which method does C use?
● If I have the name of a function in the form of a string, how
can I invoke that function?
● What does the error, invalid redeclaration of a function mean?
● How can I pass the variable argument list passed to one
function to another function.
● How do I pass a variable number of function pointers to a
variable argument (va_arg) function?
● Will C allow passing more or less arguments than required to a
function.
● Whats the difference between gets() and fgets()? Whats the
correct way to use fgets() when reading a file?
● How can I have a variable field width with printf?
● How can I specify a variable width in a scanf() format string?
● How can I convert numbers to strings (the opposite of atoi)?
● Why should one use strncpy() and not strcpy()? What are the
problems with strncpy()?
● How does the function strtok() work?
● Why do we get the floating point formats not linked error?
● Why do some people put void cast before each call to printf()?
● What is assert() and when would I use it?
● What do memcpy(), memchr(), memcmp(), memset(), strdup
(), strncat(),strcmp(), strncmp(), strcpy(), strncpy(), strlen(),
strchr(), strchr(),strpbrk(), strspn(), strcspn(), strtok() do?
● What does alloca() do?
● Can you compare two strings like string1==string2? Why do we
need strcmp()?
● What does printf() return?
● What do setjmp() and longjump() functions do?
● Whats the prototype of main()? Can main() return a structure?
● Is exit(status) equivalent to returning the same status from
main()?
● Can main() be called recursively?
● How to print the arguments recieved by main()?

Structures, Unions, and Enumerations


● Can structures be assigned to variables and passed to and
from functions?
● Can we directly compare two structures using the == operator?
● Can we pass constant values to functions which accept
structure arguments?
● How does one use fread() and fwrite()? Can we read/write
structures to/from files?
● Why do structures get padded? Why does sizeof() return a
larger size?
● Can we determine the offset of a field within a structure and
directly access that element?
● What are bit fields in structures?
● What is a union? Where does one use unions? What are the
limitations of unions?

Preprocessors ( Macros,Headers etc. )


● How should we write a multi-statement macro?
● How can I write a macro which takes a variable number of
arguments?
● What is the token pasting operator and stringizing operator in
C?
● Define a macro called SQR which squares a number.
● What should go in header files? How to prevent a header file
being included twice? Whats wrong with including more
headers?
● Is there a limit on the number of characters in the name of a
header file?
● Is it acceptable to declare/define a variable in a C header?

Bit Fiddling
● Write a C program to count bits set in an integer?
● What purpose do the bitwise and, or, xor and the shift
operators serve?
● How to reverse the bits in an interger?
● Check if the 20th bit of a 32 bit integer is on or off?
● How to reverse the odd bits of an integer?
● How would you count the number of bits set in a floating point
number?

File Operations
● How do stat(), fstat(), vstat() work? How to check whether a
file exists?
● How can I insert or delete a line (or record) in the middle of a
file?
● How can I recover the file name using its file descriptor?
● How can I delete a file? How do I copy files? How can I read a
directory in a C program?
● Whats the use of fopen(), fclose(), fprintf(), getc(), putc(),
getw(), putw(), fscanf(), feof(), ftell(), fseek(), rewind(), fread
(), fwrite(), fgets(), fputs(), freopen(), fflush(), ungetc()?
● How to check if a file is a binary file or an ascii file?
Compiling and Linking
● How to list all the predefined identifiers?
● How the compiler make difference between C and C++?
● What are the general steps in compilation?
● What are the different types of linkages?
● What do you mean by scope and duration?
● What are makefiles? Why are they used?

Linked Lists
● How do you reverse a singly linked list? How do you reverse a
doubly linked list? Write a C program to do the same.
● Given only a pointer to a node to be deleted in a singly linked
list, how do you delete it?
● How do you sort a linked list? Write a C program to sort a
linked list.
● How to declare a structure of a linked list?
● Write a C program to implement a Generic Linked List.
● How do you reverse a linked list without using any C pointers?
● How would you detect a loop in a linked list? Write a C
program to detect a loop in a linked list.
● How do you find the middle of a linked list? Write a C program
to return the middle of a linked list
● If you are using C language to implement the heterogeneous
linked list, what pointer type will you use?
● How to compare two linked lists? Write a C program to
compare two linked lists.
● How to create a copy of a linked list? Write a C program to
create a copy of a linked list ?
● Write a C program to free the nodes of a linked list.
● Can we do a Binary search on a linked list?
● Write a C program to return the nth node from the end of a
linked list.
● How would you find out if one of the pointers in a linked list is
corrupted or not?
● Write a C program to insert nodes into a linked list in a sorted
fashion?
● Write a C program to remove duplicates from a sorted linked
list?
● How to read a singly linked list backwards?
● How can I search for data in a linked list?

Trees
● Write a C program to find the depth or height of a tree.
● Write a C program to determine the number of elements (or
size) in a tree.
● Write a C program to delete a tree (i.e, free up its nodes)
● Write C code to determine if two trees are identical
● Write a C program to find the mininum value in a binary search
tree.
● Write a C program to compute the maximum depth in a tree?
● Write a C program to create a mirror copy of a tree (left nodes
become right and right nodes become left)!
● Write C code to return a pointer to the nth node of an inorder
traversal of a BST.
● Write C code to implement the preorder(), inorder() and
postorder() traversals. Whats their time complexities?
● Write a C program to create a copy of a tree
● Write C code to check if a given binary tree is a binary search
tree or not?
● Write C code to implement level order traversal of a tree.
● Write a C program to delete a node from a Binary Search Tree?
● Write C code to search for a value in a binary search tree
(BST).
● Write C code to count the number of leaves in a tree
● Write C code for iterative preorder, inorder and postorder tree
traversals
● Can you construct a tree using postorder and preorder
traversal?
● Construct a tree given its inorder and preorder traversal
strings. Similarly construct a tree given its inorder and post
order traversal strings.
● Find the closest ancestor of two nodes in a tree.
● Given an expression tree, evaluate the expression and obtain a
paranthesized form of the expression.
● How do you convert a tree into an array?
● What is an AVL tree?
● How many different trees can be constructed using n nodes?
● A full N-ary tree has M non-leaf nodes, how many leaf nodes
does it have?
● Implement Breadth First Search (BFS) and Depth First Search
(DFS)
● Write pseudocode to add a new node to a Binary Search Tree
(BST)
● What is a threaded binary tree?

Sorting
● What is heap sort?
● What is the difference between Merge Sort and Quick sort?
● Give pseudocode for the mergesort algorithm
● Implement the bubble sort algorithm. How can it be improved?
Write the code for selection sort, quick sort, insertion sort.
● How can I sort things that are too large to bring into memory?

Frequently Asked Programs


● Write your own C program to implement the atoi() function
● Implement the memmove() function. What is the difference
between the memmove() and memcpy() function?
● Write C code to implement the strstr() (search for a substring)
function.
● Write your own printf() function in C
● Implement the strcpy() function.
● Implement the strcmp(str1, str2) function.
● Implement the substr() function in C.
● Write your own copy() function
● Write C programs to implement the toupper() and the isupper()
functions
● Write a C program to implement your own strdup() function.
● Write a C program to implement the strlen() function
● Write your own strcat() function
● Write a C program to swap two variables without using a
temporary variable
● What is the 8 queens problem? Write a C program to solve it.
● Write a C program to print a square matrix helically.
● Write a C program to reverse a string
● Write a C program to reverse the words in a sentence in place.
● Write a C program generate permutations.
● Write a C program for calculating the factorial of a number
● Write a C program to calculate pow(x,n)?
● Write a C program which does wildcard pattern matching
algorithm
● How do you calculate the maximum subarray of a list of
numbers?
● How to generate fibonacci numbers? How to find out if a given
number is a fibonacci number or not? Write C programs to do
both.
● Solve the Rat In A Maze problem using backtracking.
● What Little-Endian and Big-Endian? How can I determine
whether a machine's byte order is big-endian or little endian?
How can we convert from one to another?
● Write C code to solve the Tower of Hanoi problem.
● Write C code to return a string from a function
● Write a C program which produces its own source code as its
output
● Write a C progam to convert from decimal to any base (binary,
hex, oct etc...)
● Write C code to check if an integer is a power of 2 or not in a
single line?
● Write a C program to find the GCD of two numbers.
● Finding a duplicated integer problem
● Write code to remove duplicates in a sorted array.
● Find the maximum of three integers using the ternary operator.
● How do you initialize a pointer inside a function?
● Write C code to dynamically allocate one, two and three
dimensional arrays (using malloc())
● How would you find the size of structure without using sizeof
()?
● Write a C program to multiply two matrices.
● Write a C program to check for palindromes.
● Write a C program to convert a decimal number into a binary
number.
● Write C code to implement the Binary Search algorithm.
● Wite code to evaluate a polynomial.
● Write code to add two polynomials
● Write a program to add two long positive numbers (each
represented by linked lists).
● How do you compare floating point numbers?
● What's a good way to implement complex numbers in C?
● How can I display a percentage-done indication on the screen?
● Write a program to check if a given year is a leap year or not?
● Is there something we can do in C but not in C++?
● How to swap the two nibbles in a byte ?
● How to scan a string till we hit a new line using scanf()?
● Write pseudocode to compare versions (like 115.10.1 vs
115.11.5).
● How do you get the line numbers in C?
● How to fast multiply a number by 7?
● Write a simple piece of code to split a string at equal intervals
● Is there a way to multiply matrices in lesser than o(n^3) time
complexity?
● How do you find out if a machine is 32 bit or 64 bit?
● Write a program to have the output go two places at once (to
the screen and to a file also)
● Write code to round numbers
● How can we sum the digits of a given number in single
statement?
● Given two strings A and B, how would you find out if the
characters in B were a subset of the characters in A?
● Write a program to merge two arrays in sorted order, so that if
an integer is in both the arrays, it gets added into the final
array only once. *
● Write a program to check if the stack grows up or down
● How to add two numbers without using the plus operator?
● How to generate prime numbers? How to generate the next
prime after a given prime?
● Write a program to print numbers from 1 to 100 without using
loops!
● Write your own trim() or squeeze() function to remove the
spaces from a string.
● Write your own random number generator function in C.*
● Write your own sqrt() function in C
Posted by prashanth at 6:15 AM 0 comments

Labels: Important C Questions With answers

Monday, May 28, 2007


C/C++ Faqs Collection 1

C++ on Unix
1. What is a Make file?(Fujitsu) Make file is a utility in Unix to
help compile large programs. It helps by only compiling the
portion of the program that has been changed.
2. What is deadlock? (Novell) Deadlock is a situation when two
or more processes prevent each other from running.Example: if
T1 is holding x and waiting for y to be free and T2 holding y
and waiting for x to be free deadlock happens.
3. What is semaphore? (Novell) Semaphore is a special
variable, it has two methods: up and down. Semaphore
performs atomic operations, which means ones a semaphore is
called it can not be inturrupted.
4. Is C an object-oriented language? (Microsoft) C is not an
object-oriented language, but limited object-oriented
programming can be done in C.
5. Name some major differences between C++ and Java.
C++ has pointers; Java does not. Java is platform-independent;
C++ is not. Java has garbage collection; C++ does no

Advanced C++ and STL


Questions
: How do you link a C++ program to C functions?
A: By using the extern "C" linkage specification around the C function
declarations.

Q: Explain the scope resolution operator.


A: It permits a program to reference an identifier in the global scope
that has been hidden by another identifier with the same name in the
local scope.

Q: What are the differences between a C++ struct and C++


class?
A: The default member and base-class access specifiers are
different.

Q: How many ways are there to initialize an int with a constant?


A: Two.

There are two formats for initializers in C++ as shown in the example
that follows. The first format uses the traditional C notation. The
second format uses constructor notation.

int foo = 123;

int bar (123);

Q: How does throwing and catching exceptions differ from using


setjmp and longjmp?
A: The throw operation calls the destructors for automatic objects
instantiated since entry to the try block.
Q: What is your reaction to this line of code?
delete this;
A: It’s not a good practice.

Q: What is a default constructor?


A: A constructor that has no arguments.

Q: What is a conversion constructor?


A: A constructor that accepts one argument of a different type.

Q: What is the difference between a copy constructor and an


overloaded assignment operator?
A: A copy constructor constructs a new object by using the content
of the argument object. An overloaded assignment operator assigns
the contents of an existing object to another existing object of the
same class.

Q: When should you use multiple inheritance?


A: There are three acceptable answers: "Never," "Rarely," and "When
the problem domain cannot be accurately modeled any other way."

Q: What is a virtual destructor?


A: The simple answer is that a virtual destructor is one that is
declared with the virtual attribute.

Q: Explain the ISA and HASA class relationships. How would you
implement each in a class design?
A: A specialized class "is" a specialization of another class and,
therefore, has the ISA relationship with the other class. An Employee
ISA Person. This relationship is best implemented with inheritance.
Employee is derived from Person. A class may have an instance of
another class. For example, an employee "has" a salary, therefore the
Employee class has the HASA relationship with the Salary class. This
relationship is best implemented by embedding an object of the
Salary class in the Employee class.

Q: When is a template a better solution than a base class?


A: When you are designing a generic class to contain or otherwise
manage objects of other types, when the format and behavior of
those other types are unimportant to their containment or
management, and particularly when those other types are unknown
(thus, the genericity) to the designer of the container or manager
class.

Q: What is a mutable member?


A: One that can be modified by the class even when the object of
the class or the member function doing the modification is const.

Q: What is an explicit constructor?


A: A conversion constructor declared with the explicit keyword. The
compiler does not use an explicit constructor to implement an implied
conversion of types. It’s purpose is reserved explicitly for
construction.

Q: What is the Standard Template Library?


A: A library of container templates approved by the ANSI committee
for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic
programming model, iterators, allocators, algorithms, and such, has a
higher than average understanding of the new technology that STL
brings to C++ programming.

Q: Describe run-time type identification.


A: The ability to determine at run time the type of an object by using
the typeid operator or the dynamic_cast operator.

Q: What problem does the namespace feature solve?


A: Multiple providers of libraries might use common global identifiers
causing a name collision when an application tries to link with two or
more such libraries. The namespace feature surrounds a library’s
external declarations with a unique namespace that eliminates the
potential for those collisions.
This solution assumes that two library vendors don’t use the same
namespace identifier, of course.

Q: Are there any new intrinsic (built-in) data types?


A: Yes. The ANSI committee added the bool intrinsic type and its
true and false value keywords.

Get Java Certified - Fast Job Interview?


Accelerated Java Training. Guaranteed Proven answers to tough interview
Cert. View Courses Now! questions. Get Hired!

C++ Coding Interview


Questions
Design and implement a String class that satisfies the following:

● Supports embedded nulls


● Provide the following methods (at least)
❍ Constructor

❍ Destructor

❍ Copy constructor

❍ Assignment operator

❍ Addition operator (concatenation)

❍ Return character at location

❍ Return substring at location

❍ Find substring

● Provide versions of methods for String and for char* arguments

2. Given the following classes

class Fruit {
// …
}

class Apple : public Fruit {


// …
}

class Peach : public Fruit {


// …
}

// Container of fruit
class BasketOfFruit {
BasketOfFruit() ;
void insert( Fruit & f ) ;
// …
}

// Container of apples
class BasketOfApples /* ??? */ {
// …
}

Should BasketOfApples derive from BasketOfFruit? Why or why not?


What is the general principle that determines the answer?
3. Describe briefly what the following function does. What standard
function is it most like ?

int f( char *p ) {
int n = 0 ;
while ( *p != 0 ) n = 10*n + *p++ - ‘0′ ;
return n ;
}

4. Describe briefly what function ‘a’ does in the following code


fragment.

struct s {
struct s *next ;
}

a( struct s *p, struct s *x ) {


while ( p->next != 0 ) p = p->next ;
p->next = x ;
x->next = 0 ;
}

5. What default methods are declared implicitly by the C++ compiler


for the class below:

class Empty
{
};

6. Given a system with a hard realtime priority, multithreaded


architecture, with priorities from 1 (least) to 5 (most), explain the
major flaw in the design below:

The following objects are shared between the threads:

Disk : This class is a singleton. The read() and write() methods both
block on a simple atomic lock()/unlock() shared between the two. (ie,
only one thread can access the disk, thru either read or write, at any
given time). It also has a waitForData() method, which blocks
(without claiming the lock) until either a timeout elapses, or data is
ready. It returns true upon returning due to new data, false upon
returning due to the timeout.

Network : This class is a singleton. The read() and write() methods


both block on a simple atomic lock()/unlock() shared between the
two. (ie, only one thread can access the disk, thru either read or
write, at any given time).

Sensor: The Sensor class accesses a number of physical sensors.


The first method, ‘waitForData()’, blocks until data has been
collected from the sensors. The second method, ‘processData()’,
does a series of long and cpu-intensive calculations on the data.
These calculations often take several minutes. It then returns the
processed data.

Each of the following threads is running concurrently. Assume that


the psuedocode in each thread is looped infinitely (ie, encased in a
while(true) { }. It is extremely important that information buffered to
the disk be sent to the network as quickly as possible, this is why
Thread 1 runs at priority 5. The system conditions checked in thread
3 are not particularly important events (not as important as the
calculations done in thread 2). If the events aren’t transmitted over
the network for several minutes, it’s not a problem at all. They do,
however, contain a large amount of system information. Thread 4
watches for serious system alarms, indicating serious problems.
These are a serious concern and if not quickly buffered to the disk
and sent to the network, can cause serious revenue loss.

Thread 1: (priority: 5)
while(!Disk.waitForData()) { yield(); } /* Wait until
someone has
written data to the disk */
Network.write(Disk.read()); /* Write the data buffered on
the disk to
the network */

Thread 2: (priority: 2)
while(!Sensor.waitForData()) { yield(); } /* Wait until
the sensors
have picked up data */
Disk.write(Sensor.processData()); /* process the data and
write it to
the disk. */

Thread 3: (priority: 1)

if (checkSystemCondition1()) /* If system condition 1 is


true.. */
Disk.write(SystemCond1Data); /* Grab the data on the
system
condition and buffer it to disk */
if (checkSystemCondition2()) /* see above*/
Disk.write(SystemCond2Data);
if (checkSystemCondition3()) /* see above */
Disk.write(SystemCond3Data);
yield();

Thread 4: (priority: 4)
if (checkAlarms()) /* If any serious alarms exist */
Disk.write(AlarmData); /* Buffer that data to disk for
immediate
network transmit */
yield();

Basic C++ Interview


Questions
Question: Suppose that data is an array of 1000 integers. Write
a single function call that will sort the 100 elements data [222]
through data [321].
Answer: quicksort ((data + 222), 100);

2.Question: Which recursive sorting technique always makes


recursive calls to sort subarrays that are about half size of the
original array?
Answer: Mergesort always makes recursive calls to sort subarrays
that are about half size of the original array, resulting in O(n log n)
time.

3.Question: What is the difference between an external iterator


and an internal iterator? Describe an advantage of an external
iterator.
Answer: .An internal iterator is implemented with member functions of
the class that has items to step through. .An external iterator is
implemented as a separate class that can be "attach" to the object
that has items to step through. .An external iterator has the
advantage that many difference iterators can be active
simultaneously on the same object.
4.Question: Why are arrays usually processed with for loop?
Answer: The real power of arrays comes from their facility of using an
index variable to traverse the array, accessing each element with the
same expression a[i]. All the is needed to make this work is a iterated
statement in which the variable i serves as a counter, incrementing
from 0 to a.length -1. That is exactly what a loop does.

5.Question: What is an HTML tag?


Answer: An HTML tag is a syntactical construct in the HTML
language that abbreviates specific instructions to be executed when
the HTML script is loaded into a Web browser. It is like a method in
Java, a function in C++, a procedure in Pascal, or a subroutine in
FORTRAN.

Algorithm Specific C++


Interview Questions
Q1 What are the advantages and disadvantages of B-star trees
over Binary trees? (Asked by Motorola people)

A1 B-star trees have better data structure and are faster in search
than Binary trees, but it’s harder to write codes for B-start trees.

Q2 Write the psuedo code for the Depth first Search.(Asked by


Microsoft)

A2

dfs(G, v) //OUTLINE
Mark v as "discovered"
For each vertex w such that edge vw is in G:
If w is undiscovered:
dfs(G, w); that is, explore vw, visit w, explore from there
as much as possible, and backtrack from w to v.
Otherwise:
"Check" vw without visiting w.
Mark v as "finished".

Q3 Describe one simple rehashing policy.(Asked by Motorola


people)

A3 The simplest rehashing policy is linear probing. Suppose a key K


hashes to location i. Suppose other key occupies H[i]. The following
function is used to generate alternative locations:

rehash(j) = (j + 1) mod h

where j is the location most recently probed. Initially j = i, the hash


code for K. Notice that this version of rehash does not depend on K.

Q4 Describe Stacks and name a couple of places where stacks


are useful. (Asked by Microsoft)

A4 A Stack is a linear structure in which insertions and deletions are


always made at one end, called the top. This updating policy is called
last in, first out (LIFO). It is useful when we need to check some
syntex errors, such as missing parentheses.

Q5 Suppose a 3-bit sequence number is used in the selective-


reject ARQ, what is the maximum number of frames that could
be transmitted at a time? (Asked by Cisco)
A5 If a 3-bit sequence number is used, then it could distinguish 8
different frames. Since the number of frames that could be
transmitted at a time is no greater half the numner of frames that
could be distinguished by the sequence number, so at most 4 frames
can be transmitted at a time.

C++ Networking
Question
Q: What is the difference between Stack and Queue?

A: Stack is a Last In First Out (LIFO) data structure.

Queue is a First In First Out (FIFO) data structure

Q: Write a fucntion that will reverse a string. (Microsoft)

A: char *strrev(char *s)

int i = 0, len = strlen(s);

char *str;

if ((str = (char *)malloc(len+1)) == NULL) /*cannot allocate memory


*/

err_num = 2;

return (str);

while(len)

str[i++]=s[–len];

str[i] = NULL;

return (str);

Q: What is the software Life-Cycle?

A: The software Life-Cycle are

1) Analysis and specification of the task

2) Design of the algorithms and data structures

3) Implementation (coding)

4) Testing

5) Maintenance and evolution of the system

6) Obsolescence
Q: What is the difference between a Java application and a Java
applet?

A: The difference between a Java application and a Java applet is


that a

Java application is a program that can be executed using the Java

interpeter, and a JAVA applet can be transfered to different networks

and executed by using a web browser (transferable to the WWW).

Q: Name 7 layers of the OSI Reference Model? (from Cisco)

A: -Application layer

-Presentation layer

-Session layer

-Transport layer

-Network layer

-Data Link layer

-Physical layer

C++ OOP Interview


Questions

1. How do you write a function that can reverse a linked-list?


(Cisco System)

void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur->next = head;

for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}

2. What is polymorphism?

Polymorphism is the idea that a base class can be inherited by


several classes. A base class pointer can point to its child class and
a base class array can store different child class objects.

3. How do you find out if a linked-list has an end? (i.e. the list is
not a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each
time. The second one goes at 1 nodes each time. If there is a cycle,
the one that goes 2 nodes each time will eventually meet the one
that goes slower. If that is the case, then you will know the linked-
list is a cycle.

4. How can you tell what shell you are running on UNIX system?

You can do the Echo $RANDOM. It will return a undefined variable if


you are from the C-Shell, just a return prompt if you are from the
Bourne shell, and a 5 digit random numbers if you are from the Korn
shell. You could also do a ps -l and look for the shell with the highest
PID.

5. What is Boyce Codd Normal form?

A relation schema R is in BCNF with respect to a set F of functional


dependencies if for all functional dependencies in F+ of the form a-
>b, where a and b is a subset of R, at least one of the following
holds:

● a->b is a trivial functional dependency (b is a subset of a)


● a is a superkey for schema R

C++ Job Interview


Questions
From Microsoft) Assume I have a linked list contains all of the
alphabets from ‘A’ to ‘Z’. I want to find the letter ‘Q’ in the list,
how does you perform the search to find the ‘Q’?Answer: In a
linked list, we only know about the header and other elements are
invisible unless we go through the node one by one. Since we have
go through every single node to find ‘Q’, the search time for a linked
list is linear which is O (N).

From IBM) How do you think about your school?


: I enjoy studying in our school because we have many professors
and instructors are from local companies. Their professions lead us
more close to local industries.

(From IBM) What classes you have enjoyed the most during
your school years?
Answer: I like the class I am taking this semester, which involves a
group project that needs great amount of team efforts. I really enjoy
work with a group of people because we can learn new materials
mutually.

>

m IBM) According to your group project you just mentioned, what’s


the responsibility for each member in your group?
Answer: We have five people in our group. So far we have two web
servers set up; one will be the back up system and the other will be
the main system. Our leader coordinates the schedule. Two members
are working on the database and do the coding for the connection
between database and Java serverlets. One member is working on
the user browser interface. All members will assign some classes to
work on and perform the final test at the end. We have group
meeting every Saturday to ensure our schedule is on track.

Can you work under pressure?


Answer: I worked for Sega of America in the hardware development
group three years ago. They were working on the next generation of
gaming machine (which is the “Dreamcast” we seen today in the
market). My duty was to ensure the quality of prototypes that just
built from manufacture were ready for engineers to test. I managed
to balance the schedules and pressures from school and work.

C++ Object Oriented


Interviews Questions
What is pure virtual function?
A class is made abstract by declaring one or more of its virtual
functions to be pure. A pure virtual function is one with an initializer
of = 0 in its declaration

Q. Write a Struct Time where integer m, h, s are its members


struct Time
{
int m;
int h;
int s;
};

ow do you traverse a Btree in Backward in-order?


Process the node in the right subtree
Process the root
Process the node in the left subtree

Q. What is the two main roles of Operating System?


As a resource manager
As a virtual machine

Q. In the derived class, which data member of the base class


are visible?
In the public and protected sections.

C++ Interviews Question


1. In C++, what is the difference between method
overloading and method overriding?Overloading a method
(or function) in C++ is the ability for functions of the same
name to be defined as long as these methods have different
signatures (different set of parameters). Method overriding is
the ability of the inherited class rewriting the virtual method of
the base class.

2. What methods can be overridden in Java? In C++


terminology, all public methods in Java are virtual. Therefore, all
Java methods can be overwritten in subclasses except those
that are declared final, static, and private.
3. In C, what is the difference between a static variable and
global variable? A static variable declared outside of any
function is accessible only to all the functions defined in the
same file (as the static variable). However, a global variable
can be accessed by any function (including the ones from
different files).
4. In C, why is the void pointer useful? When would you use
it? The void pointer is useful becuase it is a generic pointer
that any pointer can be cast into and back again without loss
of information.
5. What are the defining traits of an object-oriented
language? The defining traits of an object-oriented langauge
are:
❍ encapsulation

❍ inheritance

❍ polymorphism

1. What will print out?

main()
{
char *p1=“name”;
char *p2;
p2=(char*)malloc(20);
memset (p2, 0, 20);
while(*p2++ = *p1++);
printf(“%s\n”,p2);

Answer:empty string.
2. What will be printed as the result of the operation below:

main()
{
int x=20,y=35;
x=y++ + x++;
y= ++y + ++x;
printf(“%d%d\n”,x,y);

Answer : 5794
3. What will be printed as the result of the operation below:

main()
{
int x=5;
printf(“%d,%d,%d\n”,x,x< <2,x>>2);

Answer: 5,20,1
4. What will be printed as the result of the operation below:

#define swap(a,b) a=a+b;b=a-b;a=a-b;

void main()
{
int x=5, y=10;
swap (x,y);
printf(“%d %d\n”,x,y);
swap2(x,y);
printf(“%d %d\n”,x,y);
}
int swap2(int a, int b)
{
int temp;
temp=a;
b=a;
a=temp;
return 0;

Answer: 10, 5
10, 5
5. What will be printed as the result of the operation below:

main()
{
char *ptr = ” Cisco Systems”;
*ptr++; printf(“%s\n”,ptr);
ptr++;
printf(“%s\n”,ptr);

Answer:Cisco Systems
isco systems
6. What will be printed as the result of the operation below:

main()
{
char s1[]=“Cisco”;
char s2[]= “systems”;
printf(“%s”,s1);
}

Answer: Cisco
7. What will be printed as the result of the operation below:

main()
{
char *p1;
char *p2;

p1=(char *)malloc(25);
p2=(char *)malloc(25);

strcpy(p1,”Cisco”);
strcpy(p2,“systems”);
strcat(p1,p2);

printf(“%s”,p1);

Answer: Ciscosystems
8. The following variable is available in file1.c, who can access it?:

static int average;

Answer: all the functions in the file1.c can access the variable.
9. WHat will be the result of the following code?

#define TRUE 0 // some code

while(TRUE)
{

// some code

Answer: This will not go into the loop as TRUE is defined as 0.


10. What will be printed as the result of the operation below:

int x;
int modifyvalue()
{
return(x+=10);
}

int changevalue(int x)
{
return(x+=1);
}

void main()
{
int x=10;
x++;
changevalue(x);
x++;
modifyvalue();
printf("First output:%d\n",x);

x++;
changevalue(x);
printf("Second output:%d\n",x);
modifyvalue();
printf("Third output:%d\n",x);

Answer: 12 , 13 , 13
11. What will be printed as the result of the operation below:

main()
{
int x=10, y=15;
x = x++;
y = ++y;
printf(“%d %d\n”,x,y);

Answer: 11, 16
12. What will be printed as the result of the operation below:

main()
{
int a=0;
if(a==0)
printf(“Cisco Systems\n”);
printf(“Cisco Systems\n”);

Answer: Two lines with “Cisco Systems” will be printed.

Good C interview
Questions
1.

C interview questions
1 What
Interviewing Questions does
Sample questions & safe interviewing tips you can use now. static
WorkforceCentralFlorida.com
variable
mean?
Interview Answer Guide 2. What is a
Impress your interviewer and Get Hired for the job you want pointer?
www.JobInterviewTools.com
3. What is a
structure?
Behavioral Interview?
Word-for-Word Exactly What You Need To Say To Get Hired - 4. What are
Check it out! the
Behavior.Job-Interview-Answers.com differences
Java/J2EE interview Q&A between
400+ popular questions & answers with lots diagrams, examples, structures
code and
www.lulu.com/java-success
arrays?
5. In header
files
Interview Questions
whether
Find The Answers To Technical Interview Questions Here!
InterviewQuestionAndAnswer.com functions
are
Find Interview Questions declared
Ace Your Next Interview. Get 1000s Of Sample Questions. Browse or
Today! defined?
www.Vault.com
6. What are
Job Applicant Mistakes the
Five Common Job Applicant Mistakes & How to Avoid Them at differences
DiversityInc
www.DiversityInc.com between
malloc()
Software Jobs In Dallas and calloc
Verification and testing careers RIM is hiring today. Join a leader. ()?
www.Rim.com/careers
7. What are
macros?
What are
the
advantages and disadvantages?
8. Difference between pass by reference and pass by value?
9. What is static identifier?
10. Where are the auto variables stored?
11. Where does global, static, local, register variables, free
memory and C Program instructions get stored?
12. Difference between arrays and linked list?
13. What are enumerations?
14. Describe about storage allocation and scope of global,
extern, static, local and register variables?
15. What are register variables? What are the advantage of
using register variables?
16. What is the use of typedef?
17. Can we specify variable field width in a scanf() format
string? If possible how?
18. Out of fgets() and gets() which function is safe to use and
why?
19. Difference between strdup and strcpy?
20. What is recursion?
21. Differentiate between a for loop and a while loop? What
are it uses?
22. What are the different storage classes in C?
23. Write down the equivalent pointer expression for referring
the same element a[i][j][k][l]?
24. What is difference between Structure and Unions?
25. What the advantages of using Unions?
26. What are the advantages of using pointers in a program?
27. What is the difference between Strings and Arrays?
28. In a header file whether functions are declared or defined?
29. What is a far pointer? where we use it?
30. How will you declare an array of three function pointers
where each function receives two ints and returns a float?
31. What is a NULL Pointer? Whether it is same as an
uninitialized pointer?
32. What is a NULL Macro? What is the difference between a
NULL Pointer and a NULL Macro?
33. What does the error ‘Null Pointer Assignment’ mean and
what causes this error?
34. What is near, far and huge pointers? How many bytes are
occupied by them?
35. How would you obtain segment and offset addresses from
a far address of a memory location?
36. Are the expressions arr and *arr same for an array of
integers?
37. Does mentioning the array name gives the base address in
all the contexts?
38. Explain one method to process an entire string as one unit?
39. What is the similarity between a Structure, Union and
enumeration?
40. Can a Structure contain a Pointer to itself?
41. How can we check whether the contents of two structure
variables are same or not?
42. How are Structure passing and returning implemented by
the complier?
43. How can we read/write Structures from/to data files?
44. What is the difference between an enumeration and a set
of pre-processor # defines?
45. What do the ‘c’ and ‘v’ in argc and argv stand for?
46. Are the variables argc and argv are local to main?
47. What is the maximum combined length of command line
arguments including the space between adjacent
arguments?
48. If we want that any wildcard characters in the command
line arguments should be appropriately expanded, are we
required to make any special provision? If yes, which?
49. Does there exist any way to make the command line
arguments available to other functions without passing
them as arguments to the function?
50. What are bit fields? What is the use of bit fields in a
Structure declaration?
51. To which numbering system can the binary number
1101100100111100 be easily converted to?
52. Which bit wise operator is suitable for checking whether a
particular bit is on or off?
53. Which bit wise operator is suitable for turning off a
particular bit in a number?
54. Which bit wise operator is suitable for putting on a
particular bit in a number?
55. Which bit wise operator is suitable for checking whether a
particular bit is on or off?
56. Which one is equivalent to multiplying by 2?
❍ Left shifting a number by 1

❍ Left shifting an unsigned int or char by 1?

57. Write a program to compare two strings without using the


strcmp() function.
58. Write a program to concatenate two strings.
59. Write a program to interchange 2 variables without using
the third one.
60. Write programs for String Reversal. The same for
Palindrome check.
61. Write a program to find the Factorial of a number.
62. Write a program to generate the Fibonacci Series?
63. Write a program which employs Recursion?
64. Write a program which uses command line arguments.
65. Write a program which uses functions like strcmp(), strcpy
(), etc.
66. What are the advantages of using typedef in a program?
67. How would you dynamically allocate a one-dimensional and
two-dimensional array of integers?
68. How can you increase the size of a dynamically allocated
array?
69. How can you increase the size of a statically allocated
array?
70. When reallocating memory if any other pointers point into
the same piece of memory do you have to readjust these
other pointers or do they get readjusted automatically?
71. Which function should be used to free the memory
allocated by calloc()?
72. How much maximum can you allocate in a single call to
malloc()?
73. Can you dynamically allocate arrays in expanded memory?
74. What is object file? How can you access object file?
75. Which header file should you include if you are to develop
a function which can accept variable number of
arguments?
76. Can you write a function similar to printf()?
77. How can a called function determine the number of
arguments that have been passed to it?
78. Can there be at least some solution to determine the
number of arguments passed to a variable argument list
function?
79. How do you declare the following:
❍ An array of three pointers to chars

❍ An array of three char pointers

❍ A pointer to array of three chars

❍ A pointer to function which receives an int pointer

and returns a float pointer


❍ A pointer to a function which receives nothing and

returns nothing
80. What do the functions atoi(), itoa() and gcvt() do?
81. Does there exist any other function which can be used to
convert an integer or a float to a string?
82. How would you use qsort() function to sort an array of
structures?
83. How would you use qsort() function to sort the name
stored in an array of pointers to string?
84. How would you use bsearch() function to search a name
stored in array of pointers to string?
85. How would you use the functions sin(), pow(), sqrt()?
86. How would you use the functions memcpy(), memset(),
memmove()?
87. How would you use the functions fseek(), freed(), fwrite()
and ftell()?
88. How would you obtain the current time and difference
between two times?
89. How would you use the functions randomize() and random
()?
90. How would you implement a substr() function that extracts
a sub string from a given string?
91. What is the difference between the functions rand(),
random(), srand() and randomize()?
92. What is the difference between the functions memmove()
and memcpy()?
93. How do you print a string on the printer?
94. Can you use the function fprintf() to display the output on
the screen?
95. What is a linklist and why do we use it when we have
arrays? - I feel the correct answer should be linklist is used
in cases where you don’t know the memory required to
store a data structure and need to allocate is dynamically
on demand.
96. How do you detect a loop in linked list?
97. What is the difference between main() in C and main() in
C++?
98. what will be printed out when the following code is
executed:

main()
{
printf("%x",-1<<4);>

99. Programming
Interviews Questions
100. How can you defined OOP?
101. How can you use OOP in your
projects/products/applications?
102. What is copy constructor?
103. How many types of copy constructor are there?
104. What shallow copy constructor does/behaves?
105. Does C++ support copy constructor?
106. Does Java support copy constructor?
107. (If the answer to the previous question was correct) Why
doesn’t Java support copy constructor?
108. What is software life cycle?

Java/J2EE interview Q&A


400+ popular questions & answers with lots diagrams, examples,
code
www.lulu.com/java-success

Interviewing Questions
Sample questions & safe interviewing tips you can use now.
WorkforceCentralFlorida.com

Interview Answer Guide


Impress your interviewer and Get Hired for the job you want
www.JobInterviewTools.com

Interview questions
Find Only Six Figure Jobs Search 25,000 Openings
www.TheLadders.com

Memory Analyzer from SAP


Analyze Java Heap Dumps. Download Memory Analyzer
Tool from SAP.
SAP.com

Data Management issues?


Get BI, DW, Database, & KM Research and White
Papers at ITtoolbox.
research.ittoolbox.com/

UMAT Test Success


UMAT into Med, Dent, Pharm, Physio Recommended by
Doctors across Aust
www.medical-entrance.edu.au

What is a modifier? A modifier, also called a modifying


function is a member function that
changes the value of at least one data member. In other
words, an
operation that modifies the state of an object. Modifiers are
also
known as ‘mutators’. Example: The function mod is a modifier in
the
following code snippet:

class test
{
int x,y;
public:
test()
{
x=0; y=0;
}
void mod()
{
x=10;
y=15;
}
};

2. What is an accessor? An accessor is a class operation that


does not modify the state of an object. The accessor functions
need to
be declared as const operations
3. Differentiate between a template class and class
template.
Template class: A generic definition or a parameterized class
not
instantiated until the client provides the needed information. It’s
jargon for plain templates. Class template: A class template
specifies
how individual classes can be constructed much like the way a
class
specifies how individual objects can be constructed. It’s jargon
for
plain classes.
4. When does a name clash occur? A name clash occurs
when a name is defined in more than one place. For example.,
two
different class libraries could give two different classes the
same
name. If you try to use many class libraries at the same time,
there is
a fair chance that you will be unable to compile or link the
program
because of name clashes.
5. Define namespace. It is a feature in C++ to
minimize name collisions in the global name space. This
namespace
keyword assigns a distinct name to a library that allows other
libraries to use the same identifier names without creating any
name
collisions. Furthermore, the compiler uses the namespace
signature for
differentiating the definitions.
6. What is the use of ‘using’ declaration.
A using declaration makes it possible to use a name from a
namespace without the scope operator.
7. What is an Iterator class? A class that is used to
traverse through the objects maintained by a container class.
There are
five categories of iterators: input iterators, output iterators,
forward iterators, bidirectional iterators, random access. An
iterator
is an entity that gives access to the contents of a container
object
without violating encapsulation constraints. Access to the
contents is
granted on a one-at-a-time basis in order. The order can be
storage
order (as in lists and queues) or some arbitrary order (as in
array
indices) or according to some ordering relation (as in an ordered
binary tree). The iterator is a construct, which provides an
interface
that, when called, yields either the next element in the
container, or
some value denoting the fact that there are no more elements
to
examine. Iterators hide the details of access to and update of
the
elements of a container class.
The simplest and safest iterators are those that permit read-
only access to the contents of a container class.
8. List out some of the OODBMS available. GEMSTONE/OPAL
of Gemstone systems, ONTOS of Ontos, Objectivity of
Objectivity Inc,
Versant of Versant object technology, Object store of Object
Design,
ARDENT of ARDENT software, POET of POET software.
9. List out some of the object-oriented methodologies.
Object Oriented Development (OOD) (Booch 1991,1994), Object
Oriented Analysis and Design (OOA/D) (Coad and Yourdon
1991), Object
Modelling Techniques (OMT) (Rumbaugh 1991), Object Oriented
Software
Engineering (Objectory) (Jacobson 1992), Object Oriented
Analysis (OOA)
(Shlaer and Mellor 1992), The Fusion Method (Coleman 1991).
10. What is an incomplete type? Incomplete types
refers to pointers in which there is non availability of the
implementation of the referenced location or it points to some
location
whose value is not available for modification.

int *i=0x400 // i points to address 400


*i=0; //set the value of memory location
pointed by i.

Incomplete types are otherwise called uninitialized pointers.

11. What is a dangling pointer?


A dangling pointer arises when you use the address of an
object after
its lifetime is over. This may occur in situations like returning
addresses of the automatic variables from a function or using
the
address of the memory block after it is freed. The following
code snippet shows this:

class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " <<
*ptr; } }; void SomeFunc(Sample x) {
cout << "Say i am in someFunc " << s1 =" 10;">

In the above example when PrintVal() function is


called it is called by the pointer that has been freed by the
destructor in SomeFunc.

12. Differentiate between the message and method.


Message:
❍ Objects communicate by sending messages to each other.

❍ A message is sent to invoke a method.

Method

❍ Provides response to a message.


❍ It is an implementation of an operation.
13. What is an adaptor class or Wrapper class?
A class that has no functionality of its own. Its member
functions hide
the use of a third party software component or an object with
the
non-compatible interface or a non-object-oriented
implementation.
14. What is a Null object? It is an object of some
class whose purpose is to indicate that a real object of that
class
does not exist. One common use for a null object is a return
value from
a member function that is supposed to return an object with
some
specified properties but cannot find such an object.
15. What is class invariant? A class invariant is a
condition that defines all valid states for an object. It is a
logical
condition to ensure the correct working of a class. Class
invariants
must hold when an object is created, and they must be
preserved under
all operations of the class. In particular all class invariants are
both preconditions and post-conditions for all operations or
member
functions of the class.
16. What do you mean by Stack unwinding? It is a
process during exception handling when the destructor is called
for all
local objects between the place where the exception was
thrown and
where it is caught.
17. Define precondition and post-condition to a member
function.
Precondition: A precondition is a condition that must be true on
entry
to a member function. A class is used correctly if preconditions
are
never false. An operation is not responsible for doing anything
sensible if its precondition fails to hold. For example, the
interface
invariants of stack class say nothing about pushing yet another
element
on a stack that is already full. We say that isful() is a
precondition
of the push operation. Post-condition: A post-condition is a
condition
that must be true on exit from a member function if the
precondition
was valid on entry to that function. A class is implemented
correctly
if post-conditions are never false. For example, after pushing an
element on the stack, we know that isempty() must necessarily
hold.
This is a post-condition of the push operation.
18. What are the conditions that have to be met for a
condition to be an invariant of the class?
❍ The condition should hold at the end of every

constructor.
❍ The condition should hold at the end of every mutator

(non-const) operation.
19. What are proxy objects? Objects that stand for other
objects are called proxy objects or surrogates.

template
class Array2D
{
public:
class Array1D
{
public:
T& operator[] (int index);
const T& operator[] (int index)const;
};
Array1D operator[] (int index);
const Array1D operator[] (int index) const;
};

The following then becomes legal:

Array2Ddata(10,20);
cout<

Here data[3] yields an Array1D object


and the operator [] invocation on that object yields the float in
position(3,6) of the original two dimensional array. Clients of the
Array2D class need not be aware of the presence of the
Array1D class.
Objects of this latter class stand for one-dimensional array
objects
that, conceptually, do not exist for clients of Array2D. Such
clients
program as if they were using real, live, two-dimensional
arrays. Each
Array1D object stands for a one-dimensional array that is
absent from a
conceptual model used by the clients of Array2D. In the above
example,
Array1D is a proxy class. Its instances stand for one-
dimensional
arrays that, conceptually, do not exist.

20. Name some pure object oriented languages. Smalltalk,


Java, Eiffel, Sather.
21. Name the operators that cannot be overloaded.
sizeof, ., .*, .->, ::, ?: Salam in the comments notes that ->
can be overloaded.
22. What is a node class? A node class is a class that,
❍ relies on the base class for services and implementation,

❍ provides a wider interface to the users than its base

class,
❍ relies primarily on virtual functions in its public interface

❍ depends on all its direct and indirect base class

❍ can be understood only in the context of the base class

❍ can be used as base for further derivation

❍ can be used to create objects.

A node class is a class that has added new services or


functionality beyond the services inherited from its base class.

23. What is an orthogonal base class?


If two base classes have no overlapping methods or data they
are said
to be independent of, or orthogonal to each other. Orthogonal
in the
sense means that two classes operate in different dimensions
and do not
interfere with each other in any way. The same derived class
may
inherit such classes with no difficulty.
24. What is a container class? What are the types of container
classes?

A container class is a class that is used to hold objects in


memory or
external storage. A container class acts as a generic holder. A
container class has a predefined behavior and a well-known
interface. A
container class is a supporting class whose purpose is to hide
the
topology used for maintaining the list of objects in memory.
When a
container class contains a group of mixed objects, the
container is
called a heterogeneous container; when the container is
holding a group
of objects that are all the same, the container is called a
homogeneous
container.

Memory Analyzer from SAP Job Interview?


Analyze Java Heap Dumps. Download Proven answers to tough interview
Memory Analyzer Tool from SAP. questions. Get Hired!

Interview questions on
C/C++
Q1: Tell how
Interviewing Questions to check
Sample questions & safe interviewing tips you can use now. whether a
WorkforceCentralFlorida.com
linked list is
circular.
Java/J2EE interview Q&A
400+ popular questions & answers with lots diagrams, examples,
code A: Create two
www.lulu.com/java-success pointers, each
Interview Answer Guide set to the
Increase your chance of being hired With easy to follow answer start of the
guide. list. Update
www.JobInterviewTools.com
each as
follows:
interview questions
Find 70,000 jobs that pay over $100,000. Search now.
www.TheLadders.com while
(pointer1) {
pointer1 =
pointer1-
Interview Answer Guide >next;
Increase your chance of being hired With easy to follow
pointer2 =
answer guide.
www.JobInterviewTools.com pointer2-
>next; if
(pointer2)
Memory Analyzer from SAP pointer2=poin
Download Java Heap Dump Analyzer Free From SAP ter2->next;
Developer Network.
SAP.com if (pointer1
== pointer2)
{
Java Training print
Accelerated, Professional Java Training & Certification. ("circularn")
Get Info!
www.TrainingCamp.com ;
}
}

Q2: OK, why does this work?

If a list is circular, at some point pointer2 will wrap around and be


either at the item just before pointer1, or the item before that. Either
way, it’s either 1 or 2 jumps until they meet.

How can you quickly find the number of elements stored in a a)


static array b) dynamic array ?

Why is it difficult to store linked list in an array?

How can you find the nodes with repetetive data in a linked list?

Write a prog to accept a given string in any order and flash error
if any of the character is different. For example : If abc is the
input then abc, bca, cba, cab bac are acceptable but aac or bcd are
unacceptable.

This is a C question that I had for an intern position at Microsoft:


Write out a function that prints out all the permutations of a string.
For example, abc would give you abc, acb, bac, bca, cab, cba. You
can assume that all the characters will be unique. After I wrote out
my function, he asked me to figure out from the code how many
times the printf statement is run, and also questions on optimizing my
algorithm.

What’s the output of the following program? Why?

#include
main()
{
typedef union
{
int a;
char b[10];
float c;
}
Union;
Union x,y = {100};
x.a = 50;
strcpy(x.b,"hello");
x.c = 21.50;
printf("Union x : %d %s %f n",x.a,x.b,x.c );
printf("Union y :%d %s%f n",y.a,y.b,y.c);
}

Given inputs X, Y, Z and operations | and & (meaning bitwise OR


and AND, respectively)

What is output equal to in

output = (X &amp;amp; Y) | (X & Z) | (Y & Z)

Windows Programming
Interview Questions
1. What are
Software Jobs In Dallas kernel
objects? - -
Verification and testing careers RIM is hiring today. Join a leader.
www.Rim.com/careers
Several types
of kernel
Interviewing Questions objects, such
Sample questions & safe interviewing tips you can use now. as access
WorkforceCentralFlorida.com
token objects,
event objects,
Java/J2EE interview Q&A
400+ popular questions & answers with lots diagrams, examples, file objects,
code file-mapping
www.lulu.com/java-success objects, I/O
Memory Analyzer from SAP completion
Download Java Heap Dump Analyzer Free From SAP Developer port objects,
Network. job objects,
SAP.com
mailslot
objects, mutex
objects, pipe
Interview Answer Guide objects,
Increase your chance of being hired With easy to follow process
answer guide.
www.JobInterviewTools.com objects,
semaphore
objects,
Memory Analyzer from SAP thread
Analyze Java Heap Dumps. Download Memory Analyzer objects, and
Tool from SAP. waitable timer
SAP.com
objects.
2. What is a
Java Training kernel
Professional Java Training & Cert. Guaranteed Cert. View object? -
Courses Now! Each kernel
www.TrainingCamp.com
object is
simply a
memory block
allocated by
the kernel and is accessible only by the kernel. This memory
block is a data structure whose members maintain information
about the object. Some members (security descriptor, usage
count, and so on) are the same across all object types, but
most are specific to a particular object type. For example, a
process object has a process ID, a base priority, and an exit
code, whereas a file object has a byte offset, a sharing mode,
and an open mode.
3. User can access these kernel objects structures? - Kernel
object data structures are accessible only by the kernel
4. If we cannot alter these Kernel Object structures directly,
how do our applications manipulate these kernel objects? -
The answer is that Windows offers a set of functions that
manipulate these structures in well-defined ways. These kernel
objects are always accessible via these functions. When you
call a function that creates a kernel object, the function
returns a handle that identifies the object.
5. How owns the Kernel Object? - Kernel objects are owned by
the kernel, not by a process
6. How does the kernel object outlive the process that
created it? - If your process calls a function that creates a
kernel object and then your process terminates, the kernel
object is not necessarily destroyed. Under most circumstances,
the object will be destroyed; but if another process is using the
kernel object your process created, the kernel knows not to
destroy the object until the other process has stopped using it
7. Which is the data member common to all the kernel object
and what is the use of it? -

The usage count is one of the data members common to all


kernel object types

8. How to identify the difference between the kernel object


and user object? -

The easiest way to determine whether an object is a kernel


object is to examine the function that creates the object.
Almost all functions that create kernel objects have a
parameter that allows you to specify security attribute
information.

9. What is the purpose of Process Handle Table? -

When a process is initialized, the system allocates a handle


table for it. This handle table is used only for kernel objects,
not for User objects or GDI objects. When a process first
initializes, its handle table is empty. Then when a thread in the
process calls a function that creates a kernel object, such as
CreateFileMapping , the kernel allocates a block of memory for
the object and initializes it; the kernel then scans the process’s
handle table for an empty entry

10. Name few functions that create Kernel Objects? - HANDLE


CreateThread(…),HANDLE CreateFile(..),HANDLE
CreateFileMapping(..)HANDLE CreateSemaphore(..)etcAll
functions that create kernel objects return process-relative
handles that can be used successfully by any and all threads
that are running in the same process.
11. What is handle? - Handle value is actually the index into the
process’s handle table that identifies where the kernel object’s
information is stored.
12. How the handle helps in manipulating the kernel objects? -
Whenever you call a function that accepts a kernel object
handle as an argument, you pass the value returned by one of
the Create* functions. Internally, the function looks in your
process’s handle table to get the address of the kernel object
you want to manipulate and then manipulates the object’s data
structure in a well-defined fashion.
13. What happens when the CloseHandle(handle) is called? -
This function first checks the calling process’s handle table to
ensure that the index (handle) passed to it identifies an object
that the process does in fact have access to. If the index is
valid, the system gets the address of the kernel object’s data
structure and decrements the usage count member in the
structure; if the count is zero, the kernel destroys the kernel
object from memory.
14. You forget to call CloseHandle - will there be a memory
leak? - Well, yes and no. It is possible for a process to leak
resources (such as kernel objects) while the process runs.
However, when the process terminates, the operating system
ensures that any and all resources used by the process are
freed—this is guaranteed. For kernel objects, the system
performs the following actions: When your process terminates,
the system automatically scans the process’s handle table. If
the table has any valid entries (objects that you didn’t close
before terminating), the system closes these object handles for
you. If the usage count of any of these objects goes to zero,
the kernel destroys the object.
15. What is the need of process relative handles? - The most
important reason was robustness. If kernel object handles were
system-wide values, one process could easily obtain the handle
to an object that another process was using and wreak havoc
on that process. Another reason for process-relative handles is
security. Kernel objects are protected with security, and a
process must request permission to manipulate an object
before attempting to manipulate it. The creator of the object
can prevent an unauthorized user from touching the object
simply by denying access to it
16. How the handles are handled in the child process? - The
operating system creates the new child process but does not
allow the child process to begin executing its code right away.
Of course, the system creates a new, empty process handle
table for the child process—just as it would for any new
process. But because you passed TRUE to CreateProcess’s
bInheritHandles parameter, the system does one more thing: it
walks the parent process’s handle table, and for each entry it
finds that contains a valid inheritable handle, the system copies
the entry exactly into the child process’s handle table. The
entry is copied to the exact same position in the child process’s
handle table as in the parent’s handle table.
17. Why the entries in the parent process table and child table
are same? - It means that the handle value that identifies a
kernel object is identical in both the parent and the child
processes.
18. What about the usage count in the parent child process
tables? - The system increments the usage count of the
kernel object because two processes are now using the object.
For the kernel object to be destroyed, both the parent process
and the child process must either call CloseHandle on the
object or terminate.
19. What are Named Objects? - Method available for sharing
kernel objects across process boundaries is to name the
objects. Below are the kernel named objects 1) mutex, 2)
Events, 3) semaphore, 4) waitableTimers, 5)file mapping, 6)job
object. There are APIs to create these objects with last
parameter as the object name.
20. What do you mean by unnamed object? - When you are
creating the kernel objects with the help of API’s like
CreateMutex(, , , ,pzname). And the Pzname parameter is
NULL , you are indicating to the system that you want to
create an unnamed (anonymous) kernel object. When you
create an unnamed object, you can share the object across
processes by using either inheritance or DuplicateHandle
21. What is DuplicateHandle (API)? - Takes an entry in one
process’s handle table and makes a copy of the entry into
another process’s handle table
22. What is a thread? - A thread describes a path of execution
within a process. Every time a process is initialized, the system
creates a primary thread. This thread begins executing with the
C/C++ run-time library’s startup code, which in turn calls your
entry-point function ( main , Wmain , WinMain , or WWinMain )
and continues executing until the entry-point function returns
and the C/C++ run-time library’s startup code calls ExitProcess
23. What is the limit on per process for creating a thread? -
The number of threads a process can create is limited by the
available virtual memory and depends on the default stack size
24. What is Synchronization Objects? - Synchronization object s
are use to co-ordinate the execution of multiple threads.
25. Which kernel objects are use for Thread Synchronization
on different processes? - Event, Mutex, Semaphore
26. What is Event Object and why it is used? - Event is the
thread synchronization object to set signaled state or non-
signaled state.
27. What is signaled and non signaled state? - An event is in
signaled state means that it has the capacity to release the
threads waiting for this event to be signaled. An event is in non
signaled state means that it will not release any thread that is
waiting for this particular event.example in our project: when
user clicks the image application icon double simultaneously.
Two image application windows were created. so PAIG created
an event and set it to non-signaled state. Then the image
application will reset the event to signaled state, after this all
the threads are released.
28. APIs for creating event and set and reset the events -
CreateEvent-to create the event OpenEvent – to open already
created event SetEvent – to set the event signaled
stateRestEvent - To set the Event To non-Signaled State
29. What is Mutex Object and why it is used? - A mutex object
is a synchronization object whose state is set to signaled when
it is not owned by any thread, and non-signaled when it is
owned. For example, to prevent two threads from writing to
shared memory at the same time, each thread waits for
ownership of a mutex object before executing the code that
accesses the memory. After writing to the shared memory, the
thread releases the mutex object.
30. How do I create a Mutex? - A thread uses the CreateMutex
function to create a mutex object. The creating thread can
request immediate ownership of the mutex object and can also
specify a name for the mutex object
31. How do other threads own the mutex? - Threads in other
processes can open a handle to an existing named mutex
object by specifying its name in a call to theOpenMutex -
function. Any thread with a handle to a mutex object can use
one of the wait functions to request ownership of the mutex
object. If the mutex object is owned by another thread, the
wait function blocks the requesting thread until the owning
thread releases the mutex object using theReleaseMutex -
function.
32. What is semaphores and why it is used? - A semaphore
object is a synchronization object that maintains a count
between zero and a specified maximum value. The count is
decremented each time a thread completes a wait for the
semaphore object and incremented each time a thread releases
the semaphore. When the count reaches zero, no more threads
can successfully wait for the semaphore object state to
become signaled. The state of a semaphore is set to signaled
when its count is greater than zero, and non-signaled when its
count is zero. The semaphore object is useful in controlling a
shared resource that can support a limited number of users. It
acts as a gate that limits the number of threads sharing the
resource to a specified maximum number. For example, an
application might place a limit on the number of windows that it
creates. It uses a semaphore with a maximum count equal to
the window limit, decrementing the count whenever a window
is created and incrementing it whenever a window is closed.
The application specifies the semaphore object in call to one of
the wait functions before each window is created. When the
count is zero - indicating that the window limit has been
reached - the wait function blocks execution of the window-
creation code.

Data Management issues? Job Applicant Mistakes


Get BI, DW, Database, & KM Research Five Common Job Applicant Mistakes &
and White Papers at ITtoolbox. How to Avoid Them at DiversityInc
C & C++ Questions for
interviews
1. What is the
Java/J2EE interview Q&A output of printf
400+ popular questions & answers with lots diagrams, examples,
(”%d”)
code
www.lulu.com/java-success 2. What will
happen if I say
Interviewing Questions delete this
Sample questions & safe interviewing tips you can use now. 3. Difference
WorkforceCentralFlorida.com
between “C
structure”
Interview Answer Guide and “C++
Impress your interviewer and Get Hired for the job you want
www.JobInterviewTools.com
structure”.
4. Diffrence
between
Interview questions
a “assignment
Find Only Six Figure Jobs Search 25,000 Openings
www.TheLadders.com operator” and
a “copy
constructor”
Memory Analyzer from SAP 5. What is the
Analyze Java Heap Dumps. Download Memory Analyzer Tool from difference
SAP. between “overl
SAP.com
oading”
Data Management issues? and “overriddin
Get BI, DW, Database, & KM Research and White Papers at g”?
ITtoolbox. 6. Explain the
research.ittoolbox.com/
need
UMAT Test Success for “Virtual
UMAT into Med, Dent, Pharm, Physio Recommended by Doctors Destructor”.
across Aust
www.medical-entrance.edu.au 7. Can we
have “Virtual
Get Java Certified - Fast Constructors”?
Accelerated Java Training. Guaranteed Cert. View Courses Now! 8. What are the
www.TrainingCamp.com
different types
of
polymorphism?
9. What are
Virtual Functions? How to implement virtual functions in “C”
10. What are the different types of Storage classes?
11. What is Namespace?
12. What are the types of STL containers?.
13. Difference between “vector” and “array”?
14. How to write a program such that it will delete itself after
exectution?
15. Can we generate a C++ source code from the binary file?
16. What are inline functions?
17. What is “strstream” ?
18. Explain “passing by value”, “passing by pointer” and “passing by
reference”
19. Have you heard of “mutable” keyword?
20. What is a “RTTI”?
21. Is there something that I can do in C andnot in C++What is the
difference between “calloc” and “malloc”?
22. What will happen if I allocate memory using “new” and free it
using “free” or allocate sing “calloc” and free it using “delete”?

Potrebbero piacerti anche