0% found this document useful (0 votes)
130 views

C Interview Questions

1) The document discusses various C programming concepts including data types, derived data types, qualifiers like const and volatile, bitwise operators, and functions. 2) It provides examples of basic data types in C like char, int, float, and double. Derived data types include arrays and pointers. User defined data types include structs, unions, enums, and typedefs. 3) The document explains what qualifiers are and how const and volatile qualifiers work. Const prevents variable values from being changed while volatile instructs the compiler to reload variable values from memory rather than optimizing.

Uploaded by

ChandraShekar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views

C Interview Questions

1) The document discusses various C programming concepts including data types, derived data types, qualifiers like const and volatile, bitwise operators, and functions. 2) It provides examples of basic data types in C like char, int, float, and double. Derived data types include arrays and pointers. User defined data types include structs, unions, enums, and typedefs. 3) The document explains what qualifiers are and how const and volatile qualifiers work. Const prevents variable values from being changed while volatile instructs the compiler to reload variable values from memory rather than optimizing.

Uploaded by

ChandraShekar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

PROJECT IS VERY IMPORTANT.

MINUTE DETAILS ARE ALSO NECESSARY


Type Specifiers-
Char short signed
int long unsigned
float
double void

How many topics you know in C?


1. Datatypes
2.Compilation Stages
3.Array,String & pointer
4.Functions
5.Structure & union
6.DMA

Memory Diagram for C

How function calls work?


Function, is just a piece of code which can be referred using a name. The computer stores the data of the function
(such as arguments, local variables, return address etc.,) when a function is invoked and destroys them when the
function returns. Similarly when a function calls other functions, the caller function returns only after all the callee
functions are returned. We can infer a LIFO (last-in-first-out) scenario in this, ie., the function that is invoked last
completes first and the one invoked first completes last. So the stack becomes an obvious choice for function calls
implementation.
In the memory, the stack grows from the higher memory address to the lower memory addresses. So we have to
visualize an inverted stack. Have look at the below diagram.

Stack frame
Let me brief through all the terminologies before we get into the working.
Stack frame – The section of memory where the local variables, arguments, return address and other information
of a function are stored, is called stack frame or activation record.
Stack pointer – For function calls, a bulk of data is pushed and popped from the memory, whenever a function is
invoked and returned respectively. But we may need to access the data which is deep into the stack and it will be
inefficient to pop off all the data to do that. Hence, unlike conventional stack implementation, we have a register
called stack pointer that points to top of the stack such that all the addresses smaller than the address to which the
stack pointer points are considered as garbage and all the address larger are considered as valid.
Stack bottom – It is the highest valid address of the stack. When the stack is initialized the stack pointer points to
stack bottom.
Stack limit – It is the smallest valid address of the stack. When the stack pointer goes below this address, then
there’s stack overflow.
Frame pointer – When a new function is invoked the frame pointer points to where the stack pointer was and when
the function returns the stack pointer points back to where the frame pointer is.
Return address – It points to address (within the caller function) to which the control should pass when the callee
(current) function returns.
Static link – This comes into picture for the programming languages that support nested functions. When a function
(nested function) is defined within another function (enclosing function), the nested function may need to access the
variables of the enclosing function. Therefore, the nested function’s stack frame should be able to access the
enclosing function’s frame. This made possible by static link which points to the address of the enclosing function’s
frame.

How it works?
The working of stack differs with different programming languages. Programming languages like C, doesn’t support
nested functions and they dont need static link. Programming lanuages like Pascal support nested functions and
they use static link. There are programming languages like ML and Scheme which support both nested functions
and function-valued variables (ie., a function returned as a result of another function). I am not aware of how these
function calls work. I have discussed the working only for programming languages that support nested functions.
Consider a pseudo-C code: (This doesn’t work in C. Just using a comfortable syntax.)
int foo (int arg1)
{
int f (int arg2)
{
int i=10;
return arg2 * i;
}
int g(int arg3)
{
return f(arg3);
}
return g(arg1);
}
f and g are nested functions of foo. foo invokes g which inturn invokes f.
Stack frame – working
When the function foo invokes function g, the argument arg3 is pushed into the stack. A new section memory is
allocated for the function g and the stack pointer points to the highest unused address. The frame pointer points to
where stack pointer was. The old frame pointer is pushed ie., 1. The static link which points to the address of the
enclosing function foo is pushed, ie., 1. The return address is pushed ie., to foo.
Then when the function f is invoked the argument arg2 is pushed. Now the frame pointer points to where the stack
pointer was. The old FP is pushed ie., 3. The static link pointing to foo is pushed ie., 1. The return address is
pushed ie., to g. Then the local variable i is pushed.
When the function f returns. The stack pointer points to where stack pointer was and the frame pointer points to the
address stored as old FP in f’s stack frame.
This simply doesn’t work with languages like ML and scheme because in those, the local variables should not be
destroyed while the function returns! as they may be required for the nested callee function.
How recursive functions work?
The recursive functions work in same way as the other functions. For every recursive call a new stack frame of the
function is created. But this avoided in tail recursive calls in functional languages. In tail recursive call, each
recursive call is made to loop to the same stack frame.
Stack overflow
When the stack pointer goes below the stack limit, then there’s stack overflow. The most common cause for stack
overflow is the infinite loop in the recursive function calls. Imagine if a function is invoked recursively for infinite
times, a stack frame gets appended for every recursive call and at one point the stack pointer goes below the stack
limit and thus a stack overflow is caused.
References:
1. Understanding the stack.
2. Modern compiler implementation in ML by Andrew W. Appel

1) Basic data types in C


A datatype defines a domain of allowed values &the operations that can be
performed on those values (Ans-we cannot do the bitwise operation on the
float variables).
Char, int,float,double

2) Derived data types in C


Data types that are derived from fundamental data types are called
derived data types. Derived data types don't create a new data type;
instead, they add some functionality to the basic data types. Two derived
data type are - Array & Pointer.

User defined data type is used to create new data types. The new data
types formed from fundamental data types.4 Different user defined data
types are: struct, union, enum, typedef.

Enum- Enum is a user defined datatype which takes values from the
enumerators.
Enumerators is a user defined list of named integer constant.
Syntex-
Enum tag{member1,member2,member3,…}; //I Method
Enum tag{member1,member2,member3,…}var1,var2; //II Method
Eg.
Enum month{Jan,Feb,Mar,…}; //I Method
Result=Jan=0,Feb=1,Mar=2
Enum month{Jan,Feb=5,Mar,…}; //Also possible
Result=Jan=0,Feb=5,Mar=6

Typedef-A typedef is a user defined datatype which allows us to define a


new name for an existing datatype.
Syntax-
Typedef datatypenewname;
Eg.
Typedef int marks;

3) What is qualifier?
Size Qualifier-1)Signed 2)Unsigned(Asked In BOSCH 20-03-14)
Type Qualifier-1)Const 2)Volatile

You can use Size Qualifiers to indicate what size of number you want to
store inside your datatype.
4) const and volatile qualifier
Const & volatile are type qualifiers.

When we use const qualifier with any of the variable,it means that the
value of that variable cannot be changed by the program directly.
Eg.Const int a=10;
Const float pi=3.14;
• The use of const conveys some very useful information to someone
reading your code. In effect, declaring a parameter const tells the user
about its intended usage.
• const has the potential for generating tighter code by giving the
optimizer some additional information.
• Code that uses const liberally is inherently protected by the compiler
against inadvertent coding constructs that result in parameters being
changed that should not be. In short,they tend to have fewer bugs.

Volatile
When we are using any variable with volatile qualifier, it means that we
are instructing the compiler to turn off the optimization process for
that variable i.e. we are forcing the compiler to read the value of the
variable from the memory only, every time it encounters the program.

A volatile variable is one that can change unexpectedly. Consequently,


the compiler can make no assumptions about the value of the variable.In
particular, the optimizer must be careful toreload the variable every
time it is used instead of holding a copy in a register. Examples
ofvolatile variables are:
• Hardware registers in peripherals (for example, status registers)
• Non-automatic variables referenced within an interrupt service routine.
• Variables shared by multiple tasks in a multi-threaded application.

In particular, I'll ask them the following additional questions:

Use-Volatile is also used in the

multithreading systems.
How???

(It tells the compiler that the object is subject to sudden change for
reasons which cannot be predicted from a study of the program itself, and
forces every reference to such an object to be a genuine reference.)

The reason for having this type qualifier ismainly to do with the
problems that are encountered in real-time or embedded systems
programming using C. Imagine that you are writing code that controls a
hardware device by placing appropriate values in hardware registers at
known absolute addresses.)

5) Name the bitwise operators


There are 6 types of bitwise operators-
And,or,complement(not),xor,Right shift,left shift
6) Add two numbers using bitwise operators

7) Multiply and divide using shift operators

8) Fibonacci number program

9) Program to find x^y using inbuilt function pow() and without using
inbuilt function
//To find the power of the the given no
#include<stdio.h>

int power(int,int);

main()
{
int no,pow;
printf("Enter the no\n");
scanf("%d",&no);
printf("Enter the power you want to find\n");
scanf("%d",&pow);
//printf("Result=%d\n",no^pow); //XOR Symbol
printf("Result=%d\n",power(no,pow));
}

int power(int n,int p)


{
int i,res=1;
if(p==0)
res=1;
else
{
for(i=p;i>=1;i--)
res=res*n;
}
return res;
}

10) What is a function? Types of functions


A function is a self-containedsubprogram that performs some specific
task.

Types-
a)Library Functions(Pre Define)
These functions are present in the C library & are predefined. The source
code of the library functions are not given to the user. These functions
are pre compiled & the user gets only the object code. The object code of
the library fun() is linked to the object code of the progm by the
linker.
Fn() Definition- Predefined, precompiled& present in the library.
Fn() Declaration- In the header files (files with a .h extension)
Fn() Call- By the programmer.
Eg. Printf() is defined in the stdio.h.

b)User Defined Functions


Programmers can create their own functions for performing some specific
task.

11) What are the storage classes?(Pg 405 “C in depth”)


The storage class defines the 4 aspects of the variable(LIPS)
1-Lifetime-Time between the creation & destruction of the variable.
2-Scope-Location where the variable is available for use.
3-Initial value-Default value taken by the uninitialized variable.
4-Place of Storage-Place of memory where the storage is allocated for the
variable.

Eg.
a)auto
All the variables declared inside the block without any storage class are
considered as auto variables. We can also use auto storage class with
them. Automatic variable comes into the existence each time the function
is executed & are destroyed when the function terminates.

1-Lifetime- Function/Block
2-Scope- Function/Block
3-Initial value- Garbage
4-Place of Storage- Memory(Stack)

d)register
A register storage class is applied to the automatic variables only.
Thescope, lifetime& initial value of register variables is same as that
of the automatic variables.The only difference is that automatic
variables are stored in the memory while the register variables are
stored in the
CPU register.
We cannot use address operator (&) with that variables.Thus we cannot
scan the register variable.
Since the no. of the registers in the CPU are limited thus we can use
only limited no. of register variables.We can specify register class only
for int,char & pointer types.
If the variable other than these types is declared as register variable,
the compiler will not show error but it will considered those variables
as auto variable.
The register storage can be applied to the formal arguments of the
functions while other storage classes cannot be used.

1-Lifetime- Function/Block
2-Scope- Function/Block
3-Initial value- Garbage
4-Place of Storage- Register

b)extern (Asked in BOSCH 20-03-14)


If we want to use the variables in different files or in different
functions,then it is required to use that variable with the storage class
extern.
Definition of external variable-
Eg.float salary;
1-Definition creates the variable so memory is allocated at the time of
definition.
2-There can be only one definition.
3-The variable can be initialized with the definition & initializer
should be constant.
4-The keyword extern is not specified in the definition.(Some compilers
allow the use of the extern but it is better to omit this keyword in the
definition.)
5-The definition can be written outside the functions only. (If the
variable is defined inside function then it will be considered as auto
variable.)

Declaration of the external variable-


Eg-extern float salary;
1-Declaration doesn’t creates the variable.It only refers the variable
that has already been created somewhere,so memory is not allocated at the
time of declaration.
2-There can be many declaration.The declaration can be kept inside the
functions also(eg in different f(n)).
3-The variable cannot be initialize at the time of declaration.
4-The keyword extern is always specified in the declaration.

1-Lifetime- Program
2-Scope- Declaration to the end of the file/Function
3-Initial value- Zero
4-Place of Storage- Memory (data area)

c)static (Asked in BOSCH 20-03-14)


A static variable can be initialized only by constant or constant
expressions & other important thing is that the static variable cannot be
re initialized.
A static variable is created at the compilation time & remains alive till
the end of the progm. Thus the static variable is created only once & its
value is retained between the function calls.
subclass-
i)Local static
The variable which is defined inside the block with the static storage
class is known as the local static variable.
1-Lifetime- Program
2-Scope- Declaration to the end of the file/Function
3-Initial value- Zero
4-Place of Storage- Memory(data area)

ii)Global static
The main purpose of using the static storage class with the global
variable is information hiding. If aglobal(external) variable is used
with the static storage class then it cannot be accessed by the other
files.
1-Lifetime- Program
2-Scope- Declaration to the end of the file/Function
3-Initial value- Zero
4-Place of Storage- Memory (data area)
The data segment is a fixed-size area in memory used for static & extern
variables. The data segment is subdivided into two parts, one for
initialized variables and another for uninitialized variables.

The stack is an area of memory that starts out small and grows
automatically up to some predefined limit.

The third and final area doesn’t actually store variables but can be used
to store data pointed by variables.
Pointer variables that are assigned to the result of a call to the
malloc() function contain the address of a dynamically allocated area of
memory. This memory is in an area called the “heap.”
The heap is another area that starts out small and grows, but it grows
only when the programmer explicitly calls malloc() or other memory
allocation functions, such as calloc(). The heap can share a memory
segment with either the data segment or the stack, or it can have its own
segment. It all depends on the compiler options and operating system. The
heap, like the stack, has a limit on how much it can grow, and the same
rules apply as to how that limit is determined.

12) Explain register storage class


See above.

13) Difference between const int *p and const int *const p


Or how can we use const qualifier with the pointer?
We can use const qualifier in three ways with pointers-
1-pointer to const data
Eg. const int *p;
Int const *p;
In both these data will be const,pointer variable.
2-const pointer
Eg. Int *const p;
In this data will be variable but pointer will be const.
3-const pointer to const data
Eg. Const int * const p;
In this data as well as pointer both are const.

In
const int *p;
The value stored in the * will be constant. But the pointer can point to
any value & that value will become const.

In
const int *const p;
The pointer is constant as well as the value pointed by the variable is
also constant.

14) What is int(*p)[5]


p is pointing to the array of the 5 integers.

15) An array is defined in p1.c and can u use extern int arr[] in another
program p2.c
Yes,then the previous used array will be available for this file also.
16) How to modify value in 'a' in const int a=5 without using pointers.

17) Swap two variables without using third variable (two ways)
Int a=10,b=20;
I) B=a+b-(a=b);

II) b=a^b;
A=a^b;
B=a^b;

18) How to access/call functions using pointers or pointers to functions?


e.g int (*p)(int,int);
p is a pointer to a function which can access 2 values & return a integer
value.

19) What is a structure?


Structure in a user defined datatype which is use to group different type
of data types together under a single name.
Eg. Struct stu
{
Int rollno;
Char name[20];
};

20) Difference between structure and union.


The main difference between the structure & union is in the way the
memory is allocated for the members.
In the structure each member is allocated different memory while in the
union all members share the same memory location.
Size of the union will be the size of the largest element present in the
union.
When a variable of type union is declared. Compiler allocates sufficient
memory to hold the largest element in the union.
Thus the concept of union is used to save the memory. It is used when we
want to use the single element of the union.
Eg.In protocol making.

The use of the structures are in making database like single linked list
(symbol table),in the designing of the OS,etc.
The use of the union in protocol designing,semaphore,etc.
The other main difference between the structure & union is that we cannot
initialize all the members of the union simultaneously.

21) How to declare structures using your name (Hint: typedef)


Both are tested in linux environment

1)Typedef Struct stu


{
Int rollno;
Char name[20];
Float marks;
}student;
Student a;

2)
#define student struct stu \
{ \
Int rollno; \
Char name[20]; \
Float marks; \
} \

Student a;

22) Which are constants if you define a structure like(To ask???)


const struct s{int a; int *p;}*q; How to implement progm 47.c of
vectorOldQ
L
23) What is structure padding?
The process of putting the padding bytes in the structure is known as
structure padding.
The reason of structure padding is thatthe members of the structure must
appear at the correct byte boundary. It increases the speed of the
program execution because it is faster &easier for the complier to fetch
the value from the memory addresses of multiple of 4.

24) What is the size of a given structure?


Sizeof(struct)=sum of size of field + alignment padding(processor &
compiler specific)

25) What is the size of a given union?


Size of the union will be the size of the largest element present in the
union.

26) What is preprocessor directives?


# is known as preprocessor directive & whenever the preprocessor finds a
line starting with #,it will consider that line as a command for itself &
works accordingly.
All the directive are executed by the preprocessoronly. There can be only
one directive in a line.More than one directive the line will produce
error(tested on Linux).
Only # is known as null directive.It has no effect.

27) Explain different preprocessor directives which you know? (Asked in


Bosch 20-2-14)
#include for including the header file.
#define for defining the macro (symbolic constants)
#undef for undefining the macro.
#pragma implementation based directive
Eg. #pragma name
Name is the name of the pragma we want. Any unrecognized pragma
will not produce any error.

The preprocessor directives used for the conditional compilation are-


#ifdef,#ifndef,#if,#else,#elif,#endif
Condition compilation means compilation of a part of the code based on
some condition.These conditions are checked during the preprocessor
phase.
Every #if should end with a #endif directive.

28) Write a macro to find the number of seconds in a year


(Hint: 365*24*60*60 is out of range in Turbo C)

#define sec 365*24*60*60


(working in GCC)

29) What is #pragma?


#pragma implementation based directive
Eg. #pragma name
Name is the name of the pragma we want. Any unrecognized pragma
will not produce any error.

31) Write a macro to find the biggest of two numbers.(Asked in Brigosha


Technologies)
#define BIGGER(a,b) a>b?printf(“a is bigger”):printf(“b is bigger”);
(Tested on linux)

32) Explain the concept of linking n loading?


Linking :
When the C file is compiled, the compiler generates object code. After
generating the object code, the compiler invokes the linker. One of the
main work of the linker is to make the code of library functions
available for the program. This process is known as linking.
This linking can be either static or dynamic. In static linking all the
static libraries and relocatable object modules will be present in the
executable file.
In the case dynamic linking all the shared libraries will be loaded into
the executable once it gets loaded into the memory. The advantage of
dynamiclinking is that the libraries that we add will not be part of the
executable file, so that file size gets reduced.

Loading:
Loading is bringing the executable code into the main memory
forexecution. The header record is checked to verify that there correct
program is been presented for loading. As each text record is read, the
object code it contains is moved to the indicated address in memory. When
the end record in encountered, the loader jumps to the specified address
to begin the execution of the loaded program.

What is static & dynamic library?


When the C file is compiled,the compiler generates object code. After
generating the object code,the compiler invokes the linker.One of the
main work of the linker is to make the code of library functions
available for the program. A linker can accomplish this task in two ways,
by copying the code of library function to your object code or by making
some arrangements so that the complete code of library functions is not
copied but made available at runtime.

Static Linking & Static Libraries


It is the result of the linker making copy of all used library functions
to the executable file. Static linking creates larger binary files & need
more space on the disk & main memory. Eg of static libraries are .a files
in Linux & .lib files in windows.
Steps to create static library in Linux-

Dynamic Linking &Dynamic Libraries


Dynamic linking does not require the code to be copied. The actual
linking happens when the progm is run, when both the binary file & the
library are in memory. Examples of dynamic library are .so in linux &
.dll in windows.
Steps to create dynamic library in Linux-

State the difference between the Static & dynamic library.


Static library:
1- Done by static linking.
2- Also known as archive file.
3- Creates large binary file, since the code is copied into the
executable code.
4- Independent of libraries at runtime.

Dynamic library:
1- Done by dynamic linking.
2- Also known as shared objects.
3- Creates smaller binary file.
4- Dependent of libraries at runtime.

33) Write a program to find the middle node in a single linked list using
only one for loop

34) Write a program to implement double linked list using only one
pointer(Hint: use exor operator)

Q) wirte a program in one line power of two?


int n;
n & (n-1)?printf("Number is not power of 2"):printf("Number is power of
2");

35) Difference between C and Embedded C


1)Generally we use native compilers for C & use cross compilers for
embedded C.
2)Conventional C is uP dependent while embedded C is uC dependent.
3)Since embedded C is an extension of the conventional C,Thus it will
contain all the features of the conventional C.
Embedded C will have some extra features also.
4) Conventional C is not memory specific i.e. variable cannot be put in
desired memory location. While in embedded C we can do it.
5) Conventional C is not target specific while embedded C is target
specific.

37)What is system Programming?


A system programming is the programming of the system software. The main
aim of the system programing is to provide the services to the computer
hardware. It also requires the degree of hardware awareness.

38)What is thread?
A thread is a basic unit of CPU Utilization. It comprises of a thread
ID,a PC,a register set & a stack. If different threads belongs to the
same process then they will also share its code section & other CPU
resources.
A traditional process has a single thread of control.
If a process has multiple thread of control, it can perform more than one
task at a time.

Types-
User Thread-The support for the user thread is provided at user level
without kernel support.
Kernel Thread-The support for the kernel thread is provided at kernel
level. These are supported & managed directly by OS.

User threads are easy to createand use but the disadvantage is that if
they perform a blocking system calls the kernel is engaged completely
tothe single user thread blocking other processes.
They are created in user space.Kernel threads are supported directly by
the operating system.
They are slower to create and manage. Most of the OS like Windows NT,
Windows 2000, Solaris2, BeOS, and Tru64 Unixsupport kernel threading.

What is big endian & little endian?


These are the way in which the variable is stored in the memory.
In the case of Little endian,the LSB is stored in the lower byte of the
memory.
In the case of Big endian,the LSB is stored in the higher byte of the
memory.

What happen if we will increase the frequency of oscillations of the


crystal in the micro controller? (Asked in SriVeda EmbSys)
Since,Speed is directly proportional to the frequency of
oscillations,thus the speed will increase.
But the accuracy & the performance will decrease because it may be
possible that the microcontroller do mistake in fast speed.

If we want to connect the two UART in a full duplex mode,how many of


minimum nos. of lines we need? (Asked in SriVeda EmbSys)
3 lines.
UART 1 UART 2
Tx-------------------------->Rx
Rx<--------------------------Tx
GND--------------------------GND

How we are testing the products we are developing? (Asked in HCL)


Full version of the IDE provides the simulator also, so we test the
through it.

How the slave address is decided in the I2C?


It is mentioned in the datasheet of the respective device.

Size of the CAN identifier?


On the basis of the size of the identifier the CAN is divided into 2
types-
1) Standard- 11 bit identifier
2) Extended- 29 bit identifier
Identifier is closed inside the arbitration field.

Why memory allocates the memory address in the multiple of 4?

What happens when we reset the microcontroller? (Asked in HCL,BOSCH)


When we reset the micro controller, it will terminate all the activities.
All the values present in the registers will be lost.
(In case of 8051-RESET pin is an input & is active high (normally
low).Upon applying a high pulse to this pin,the microcontroller will
reset & terminate all activities.This is often referred as power-on
reset.
Activating a power-on reset will cause all values in the register to be
lost.)

Register Reset Value


PC 0000
DPTR 0000
ACC 00
PSW 00
SP 07
Reg B 00
P0-P3 FFFF

LT= A,B,Dptr,PC,PSW,Port,SP ABD triple P SP

Which protocol is synchronous & full duplex in between I2C & SPI?
SPI = synchronous, full duplex
I2C= synchronous

What is a macro?
A macro is a fragment of code which has been given a name. Whenever the
name is used, it is replaced by the contents of the macro. There are two
kinds of macros-
i)Object-like macros resemble data objects when used,
ii)function-like macros resemble function calls.

What is inline functions?


When we use inline keyword with the function then we are instructing the
compiler to replace the function call with the function body, if
possible.
Advantage- faster execution, since function call is reduced.
Disadvantage- file size increases.
Used in C++, if we will use it in C also. It will not show any error but
do not work, see by file in preprocessor stage.
What is the difference between the macro & the inline function?
1. Macro does not perform type checking but inline function performs.

inline int max (int a, int b) { return (a > b) ? a : b; }


inline char max (char a, char b) { return (a > b) ? a : b; }
inline double max (double a, double b) { return (a > b) ? a : b; }
inline float max (float a, float b) { return (a > b) ? a : b; }

2.Inline functions are specified using the same syntax as any other
function except that they include the inline keyword in the function
declaration.

3. Expressions passed as arguments to inline functions are evaluated


once. In some cases, expressions passed as arguments to macros can be
evaluated more than once.
Eg. MAX(p++, b)

4. Macro never returns a value but inline may return depending upon its
prototype.

5. Inline function are parsed by the compiler, whereas the #define are
expanded in the preprocessor stage.

6. Macro name is always replaced by macro body whereas in case of inline


function’s it depends on the compiler.

7. Macro doesn’t make the part of code segment but inline function does.

What are the addressing ways we use in the internet?


4 ways-
1-Physical Address
2-Logical Address
3-Port Address
4-Application Specific Address

What is the way to establish a TCP connection?


TCP establishes the connection through 3 way handshaking process, where
client send a SYN segment to server. If server is ready to listen this
client, send back a SYN+ACK segment back to the client, and then client
send back an ACK segment (which is an acknowledgement packet of the SYN
it received from server)back to the server. When server received this ACK
back, the connection is said to be established between client and server.

What is the way to terminate a TCP connection?


Same as above but the name of the segment will be FIN in place of SYN.

What are the difference between TCP and UDP?


TCP:
1-Connection oriented protocol
2-acknowledged one
3-Guaranteed delivery by using 3 way handshake
4-Error Detection via using sequence & Ack No's
5-Slow
6-Windowing???

UDP:
1-Connection less protocol
2-unreliable
3-Best effort delivery but no guarantee
4-No error Detection
5-Fast
6-No Windowing???

Which layer is closer to the user?


Upper layer i.e. Application layer is closer to the user.

You are in home. But you need to access the office server router. How can
you do that?
By using "Telnet"
By using "Telnet" or "SSH"
Virtual private n/w
If you have public ip, then you can access from your home.But you have a
net connection first.

What is the data unit of "Transport layer"?


It depends on the protocol we are using eg.If it is UDP=PDU=>User
Datagram
The data unit of transport layer is "Segment".

TCP/IP has how many layers?


Four Layers namely: (PITA), (5,PDNTA according to Frouzan)
Physical Layer,
Datalink Layer,
Internet or Network Layer,
Transport Layer and
Application Layer....

How data is sent by IP layer?


IP layer PDU is "packet". So, data is send as packet.

What is the upper layer name of OSI layer?


Application layer.

What are the differences among router, switch, bridge and hub?
All of them are devices and are used in network. Their differences are:
*Router: Layer 3 device, can work on physical, data and network layer.
*Switch: Layer 2 device, can work on data link layer
*Bridge: Layer 2 device, can work on data link layer.
*Hub: Layer 1device, just a multi-port repeater and works on physical
layer

What are the differences between OSI and TCP/IP model?


Important differences are:
OSI is a reference model and TCP/IP is an implementation of OSI model.
OSI has 7 layers whereas TCP/IP has only 5 layers. The upper 3 layers of
the OSI model is combined on the TCP/IP model.

What is the full form of OSI and TCP/IP model?


OSI - Open System Interconnection
TCP/IP - Transmission Control Protocol/ Internet Protocol

What is TCP/IP model?


TCP/IP model is an implementation of OSI reference model. It has five
layers(PDNTA). They are: Network layer, Internet layer, Transport layer
and Application layer.

What is OSI model?


OSI model is a reference model containing 7 layers- (PDNTSPA) physical
layer, data link layer, network layer, transport layer, session layer,
presentation layer and application layer.
It helps us to understand the network architecture.

Which layer of OSI is responsible for end-to-end communication?


Transport layer.
End-to-end communication refer to process to process delivery which is
done by TRANSPORT LAYER through port number.
Transport layer provides transparent transfer of data between end
systems, or hosts, and is responsible for end-to-end error recovery and
flow control. It ensures complete data transfer.
End to end communication refers to host to host communication which is
done at the networking layer. The process to process communication is
done at the transport layer!!

What is the port number of ftp(data) and ftp?


ftp(data)use port no 20 and ftp use port no 21whether it is TCP or UDP
ftp(data)uses the port no is 20 and for ftp the port number is 21.here
for TCP and UDP have same port numbers.

What is the responsibilities of Network Layer?


1. Tomove packets from source to destination.
2. To provide internetworking.

Mark one of the most important difference between TCP and UDP.
TCP is a connection-oriented and UDP is a connection-less protocol

What is the difference between a NULL pointer and a void pointer?


A NULL pointer is a pointer of any type whose value is zero.
Conceptually, when a pointer has a NULL value it is not pointing
anywhere.

A void pointer is a pointer to an object of an unknown type, and is


guaranteed to have enough bits to hold a pointer to any object. A void
pointer is not guaranteed to have enough bits to point to a function
(though in general practice it does).

Basically,null pointer is a value, while void pointer is a type .

What is an interrupt? (Asked in BOSCH 20-03-14)


An interrupt is an external or internal event that interrupt the
microcontroller to inform it that a peripheral /device needs its service.
-Whenever any device needs its service it will inform the microcontroller
by sending an interrupt signal.
-Upon receiving the interrupt the microcontroller will stop whatever it
is doing & serve that device.
-The program associated with the interrupt is ISR (Interrupt service
routine) or interrupt handler.

Interrupts (6) in 8051-


1-reset power up reset
2-2 interrupts for timers
3-2 interrupts for h/w external interrupts
4-Serial comm. has a single interrupt that belongs to both receive &
transfer.

Steps for executing an interrupt-


Upon activation of the interrupt, the microcontroller goes through the
following steps-
1.It finishes the instruction it is executing & saves the address of the
next instruction (i.e. value of PC, Program Counter) on the stack.
2. It also saves the current status of all the interrupts internally (not
on stack).
3. It jumps to a fixed location in memory, called the interrupt vector
table that holds the address of the ISR.
4. After getting the address of the interrupt it jumps to it.
It starts to execute the ISR until it reaches the last instruction of the
subroutine RETI (return from interrupt)
5. After executing the RETI instruction, the microcontroller returns the
place where it was interrupted-
First, it gets the PC address from the stack by popping the top 2 bytes
of the stack into the PC.
Then it starts executing from that address.

Q-What is watchdog timer? (Asked in HCL & ARPL March-14)


A watch dog timer is an electronic timer that isused to detect and
recover from computer malfunctions.
They're used because sometimes the computer programsaren't programmed
very well and haveerrors that cause them to hang ininfinite loops.
Watch dog timers are commonly foundin embedded systems and other computer
controlled equipment where humans cannot easily access the equipment (or
would beunable to react to faults in a timely manner). In such systems,
the computer cannotdepend on a human to reboot it if it hangs; it must be
self - reliant. For example, remote embedded systems such as space probes
are notphysically accessible tohuman operators; these could become
permanently disabled if they were unable toautonomously recover from
faults.
Types-
Single stage watchdog
Multistage watchdog

What is Accumulator, CPU, Program Counterand Stack?


Accumulator (A)-It is one of the imp register. A is used to store
different values like the result of the arithmetic expression.

Program Counter(PC)-It is one of the important register of the


microcontroller. ThePC points to the next instruction to be fetched.As
each instruction is executed, the PC is incremented by one to point the
next instruction.(Asked in BOSCH 20-03-14)

Stack is a memory in which all the local auto variables & formal
arguments are stored&it also stores the function call address.

Is it necessary to use .h extension with the header files? (Asked in


ARPL 20-03-14)
No, it is not necessary to use the .h extension. Header files are given
.h extension to distinguish them from other C files, although it is not
necessary.

What is operating system?


An operatingsystem is a program that manages the computerhardware.The
operatingsystem acts as a resource allocator which manages the different
resources.(Resources Like- CPUtime,memory space, file-
storagespace,I/Odevices,andsoon).

An operatingsystem provides the environment within which programs are


executed. ENOUGH

One of the most important aspects of operatingsystems is the ability to


Multiprogram.A single user cannot keep either the CPU or the
I/Odevicesbusyatalltimes. Multiprogramming increases CPUutilizationby
organizing jobs (code and data) so that the CPUalwayshasonetoexecute.

Theideaisasfollows:Theoperatingsystemkeepsseveraljobsinmemory
Simultaneously(Figure1.7)
.Thissetofjobscanbeasubsetofthejobskeptinthejobpool—
whichcontainsalljobsthatenterthesystem—sincethenumber
ofjobsthatcanbekeptsimultaneouslyinmemoryisusuallysmallerthan
thenumberofjobsthatcanbekeptinthejobpool.Theoperatingsystem
picksandbeginstoexecuteoneofthejobsinmemory.Eventually,thejob may have to
wait forsometask,suchasanI/Ooperation,tocomplete.Inanon-multi programmed
system, the CPUwoulditidle.Inamultiprogrammed
system,theoperatingsystemsimplyswitchesto,andexecutes,another job. When
that job needs to wait, the CPUisswitchedtoanotherjob,andsoon.

Multiprogrammedsystemsprovideanenvironmentinwhichthevarious
System resources(forexample,CPU,memory,andperipheraldevices)are
utilizedeffectively,buttheydonotprovideforuserinteractionwiththe
computersystem.Timesharing(ormultitasking)isalogicalextensionof
multiprogramming. In time- sharing systems, the CPUexecutesmultiplejobs
byswitchingamongthem, but the switchesoccursofrequentlythattheusers
caninteractwitheachprogramwhileitisrunning.

What is process?
Aprogramloadedintomemoryandexecutingiscalledaprocess.
What is the advantage of virtual memory?
Inatime-sharingsystem,theoperatingsystemmustensurereasonable
responsetime,whichissometimesaccomplished throughswapping,where
processesareswappedinandoutofmainmemorytothedisk.Amorecommon
methodforachievingthisgoalisvirtualmemory,atechniquethatallows
theexecutionofaprocessthatisnotcompletelyinmemory(Chapter9).
Themainadvantageofthevirtual-memoryschemeisthatitenablesusers to
runprogramsthatarelargerthanactualphysicalmemory.

What is address bus?(Asked in ARPL)


Address bus is use for carrying the address. It is unidirectional bus &
use to carry address from microcontroller to the peripherals.

What is the difference between the signed & unsigned int? What is the
range limit of both? (Asked in Brigosha Technologies)
The signed & unsigned keywords can be applied to char & integer
datatypes.
(We cannot use it with float, it will give error=>Tested)
When the keyword unsigned is used the number is always positive & when
the keyword signed is used the number is positive or negative.If the sign
keyword is not defined then by default the variable will be signed.

The range of values for signed datatypes is less than that of unsigned
datatype. This is because in signed datatype, the leftmost bit(MSB) is
used to represent the sign,while in unsigned type this bit is also used
to represent the value.

Eg. For a 1 byte (8 bits) char-


If signed, then range will be -128 to +127.
If unsigned, then range will be 0 to +255.

What is Type Conversion? Explain its type?


The operations in which the datatype of one operand is converted into the
datatype of another operand to get a uniform type is known as type
conversion or type casting.

Type Conversion-
1-Implicit Type Conversion
a- Automatic Type Conversion
i- Automatic Unary Conversion
ii- AutomaticBinary Conversion
b- Type Conversion in Assignment

2-Explicit Type Conversion(Type Casting)

Implicit Type Conversion=These conversions are done by the C compiler


accordingto some predefined rules of the C language.
Whenever there are 2 operands of different datatypes, the operand with a
lower rank will be converted to the type of higher rank operand.This is
called the promotion of data type.

Explicit Type Conversion(Type Casting)=Type casting is done with the help


of cast operator.The cast operator is unary operator that is used for
converting an expression to a particular datatype temporarily.
Syntax-
(datatype)expression

Eg. (float)20/3 Result=6.66,constant 20 is converted to


float type & then divided by 3

(float)(20/3) Result=6.00,20 is divided by 3 & the result


of whole expression is converted to float type.

What is call by value & call by reference? What is the effect of both on
the stack size?

What is encapsulation technique?


ANSWER: Hiding data within the class and making it available only through
the methods in C++/ (functions in C). This technique is used to protect
your class against accidental changes to fields, which might leave the
class in an inconsistent state.

What does a socket consists of?


The combination of an IP address and a port number is called a socket.

Syntax= int socket(int domain,int type,int protocol)


sfd=socket(AF_INET,SOCK_DGRAM,0); //For UDP
sfd=socket(AF_INET,SOCK_STREAM,0); //For TCP

In how many parts the file management divides the hard disk?
File management divides the hard disk into 4 parts (BSID)-
1) Boot Block- OS is present in this block. All booting related
information is present in this block.
2) Super Block- It consists of file system information.
3) Inode Block- It consists of all file information.
4) Data Block- It consists of all files.

How many type of file Linux OS supports?


It supports 7 types of file(LT=RDLPCBS)-
1) Regular
2) Directory
3) Link
4) PIPE
5) Char Special file
6) Block special file
7) Socket file

What is IPC? Explain its types & also their advantages & disadvantages.
IPC stands for Inter Process Communication.
Generally we have 4 types of IPC.
a) PIPE (Unnamed Pipe)
b) FIFO (Named Pipe)
c) Message Queue
d) Shared Memory

PIPE=Oldest IPC. Also called as Unnamed PIPE because no named file is


created. In this IPC we make a file in a direct block (i.e. in RAM) &
then access it through the fd (file descriptor) available to us.
Direct Block= When we are saving the file into the RAM for temporary
purpose.
Indirect Block= When we are saving the file into hard disk.
System call use for creating the unnamed PIPE is-
Pipe(p);
Advantages- Easiest IPC
Disadvantages- Only related processes can communicate.

FIFO=In this we creates a named file in the indirect block, so that 2


different process can access it through that name (ie through the inode
present). The main hack is that we have created a reference file in which
one file is writing & other file is reading through it.
System call use for creating the named PIPE is-
Mkfifo(“f1”, 0666);
It will create the f1 named PIPE with the permission of 666, zero is for
octal.
Advantages- Two unrelated processes can communicate.
Disadvantages-1. We cannot send the data to the desired process.
2. The processes should be alive to communicate.
3. For full duplex communication we have to create 4 processes.

Message Queue=In this IPC a block of memory is created in the kernel


space & messages are shared through that area. Message Queue is useful
for exchanging smaller amounts of data. Message Queue is implemented by
using the system calls thus require more time consuming task of kernel
intervention.
Functions/System Calls Used-
Msgget- for creating a message queue.
Msgsnd-
Msgrcv-

Advantages=1. We can send the data to particular process (through message


identifier).
2. No need of the process to be alive, but system should not be shut
down.

Disadvantage=1. Slowest IPC since kernel have to manage the large data
structure & its different task like, managing the message queue,
searching the desired message.

Shared Memory=Intheshared-memorymodel,a block ofmemory is created in the


user space that issharedbycooperatingprocesses.Processescanthenexchange
informationbyreadingandwritingdatatothatsharedregion.
In shared-memory systems, systemcallsarerequiredonlytoestablishshared-
memoryregions.OncesharedMemoryisestablished,allaccessesaretreatedasroutin
ememoryaccesses,andnoassistancefromthekernelisrequired.
Functions/System Calls Used-
Shmget= for determining how much memory you want as a shared memory.
Shmat= for attaching the shared memory segment.
Shmdt= for deattaching the shared memory segment.

Advantage=1.Fastest IPC.
Disadvantage=
What is semaphore?
It is a synchronization method so that multiple processes cant access
shared resource at a time. It is a small integer value which is present
in the kernel space used for synchronization between the multiple
processes when the processes are trying to access the shared resource.
Types- a)Mutex b)Normal Semaphore.

Mutex Semaphore (Mutually Exclusive Event) The process which locks the
key have the authority to unlock the key also.
Normal Semaphore If one process locked the key other process has
authority to unlock the key also.

Using semaphore we cannot exchange the data between the two processes.

What is a callback function & its use?


Ans-E:\Study Material\Resume terms\Callback
A callback is a piece of executable code which is passed as an argument
to other code, which is expected to execute/callback the argument at some
convenient time. The invocation may be immediate as in a synchronous
callback or it might happen at later time, as in an asynchronous
callback.

What is the range of the temp sensor you have used?(Asked in BOSCH 20-03-
14)
-50oC to +150oC

What will be the minimum & maximum voltage reading at that minimum
&maximum temperature?(Asked in BOSCH 20-03-14)

On which principles the temperature sensors work?(Asked in BOSCH 20-03-


14)
May be the R varies at different temp.

Why you haven’t used thermometer to measure the temp of the room?(Asked
in BOSCH 20-03-14)
(They just want to listen that thermometer (we use to measure the temp of
body) is not having negative temp scale)

What are the criteria on which you have selected the temperature sensor?
(Asked in BOSCH 20-03-14)
1-Range
LM35=-50oC to +150oC
LM35C=-40oC to +110oC
LM35D=0oC to +100oC
2-Calibrated directly in oC-While some of the temperature sensors are
calibrated to oKelvin scale.
3-It draws very less current of 60 microA.
4-Low self-heating(<0.1oC in still air).
5-Linear output.

What are the criteria on which you have selected the RTC?
1-It can be able to show sec, min, hour, date, month, day, year/leap year
& valid up to 2100.
2-Consumes less than 500nA current.
3-Working temp range= -40oC to 85oC.
5-Low power required.
6-Built in battery.

56 bytes non-volatile(NV) SRAM.


The contents of the time & calendar reg are in the BCD format.

What is the working principle of ADC MCP3204?


Successive Approximation

Why you have chosen the SPI protocol for interfacing the ADC MCP3204?
It is having following advantages-
1- It provides arbitrary choice of message size, content & purpose
i.e. it is not limited to 8 bits words. Since our ADC is having 12
bit of resolution.(Main point to use in our project)
2- Requires lower power than I2C.
Power required by I2C=
Power required by SPI=
I2C draws more power than other serial communication buses due to open
drain topology of the communication lines.
3- Slaves use the master’s clock, & don’t need precision oscillators.
4- Slave don’t need a unique address – unlike I2C.
5- Uses only 4 wires which is less than wires used in the parallel
interfaces. (Main point to use in our project)
6- Only a signal is required to select the slave (chip select).
(Main point to use in our project).
7- Full duplex communication.
8- With only a single SPI slave, you *might* not need the CS. (Main
point to use in our project).
9- For single-direction SPI , you *might * only need one of
MOSI or MISO; (Main point to use in our project).
If you only have one SPI slave (e.g. a high speed ADC or DAC), you
can’t ie the device's CS to active and use the SCLK to trigger the
slave to output data (MISO) or to receive data (MOSI ).

Disadvantages-
1- Requires more pins as compares to I2C.
2- No hardware flow control???
3- No hardware slave acknowledgement unlike I2C.
4- Supports only one master device.
5- Only handles short distances compared to RS-232, RS-485 & CAN BUS.

Why you have chosen the I2C protocol for interfacing the RTC DS1307?
Advantages-
1- It is only 2 wire protocol.
2- If your system needs to access multiple devices on a relatively
slow frequency eg. In terms of hundreds or thousands of msec, or
requires multiple masters to access one or more slave devices, I2C
is the choice. If your system only needs to access one high speed
slave device, SPI is a better choice.
3- Flexible data transmission rates.
4- Each device on the bus is independently addressable.
5- Numbers of slaves can be connected according to the addressing
scheme used.

Disadvantages-
1- Slaves of the same address are not possible.
2- Speed is quite slower as compare to SPI.
3- The shared nature of the I2C bus can result in the entire bus
hanging when a single device on the bus stops operating.
4- Use more power than SPI.

What are the differences between UART & USART? (Asteria Aerospace)
USART chips have synchronous & asynchronous modes.In synchronous
transmission,the clock data is recovered separately from the data stream
& no start/stop bits are used. This improves the efficiency of the
transmission on suitable channels since more of the bits sent are usable
data & not character framing. An asynchronous transmission sends no
characters over the interconnection when the transmitting device has
nothing to send,but a synchronous interface must send “pad” characters to
maintain synchronization between the receiver& transmitter. The usual
filler is ASCII “SYN” character. This may be done automatically by the
transmitting device.

What the advantages & disadvantages of UART?

If the slave of desired address is not present in the network,then what


will happen in the I2C protocol?

Speed of sound in air?


343 metres per second= 1,234 kilometres per hour (767 mph)=(1,125 ft/s)
Speed of ultrasonic waves in air?
343 metres per second= 1,234 kilometres per hour (767 mph)=(1,125 ft/s)

What is the difference between declaring a variable and defining a


variable?
Answer:
Declaring a variable means describing its type to the compiler but not
allocating any space for it. Defininga variable means declaring it and
also allocating space to hold the variable. You can also initialize a
variableat the time it is defined. Here is a declaration of a variable
and a structure, and two variable definitions, onewith initialization:
extern int decl1; /* this is a declaration */
struct decl2 {
int member;
}; /* this just declares the type--no variable mentioned */
int def1 = 8; /* this is a definition */
int def2; /* this is a definition */
To put it another way, a declaration says to the compiler, “Somewhere in
my program will be a variable withthis name, and this is what type it
is.” A definition says, “Right here is this variable with this name and
thistype.”

A variable can be declared many times, but it must be defined exactly


once. For this reason, definitions do not belong in header files, where
they might get #included into more than one place in your program.

What is a callback function? (Imp)


A callback is a piece of executable code that is passed as an argument to
other code, which is expected to call back (execute) the argument at some
convenient time. The invocation may be immediate as in a synchronous
callback or it might happen at later time, as in an asynchronous
callback.
There are two types of callbacks: blocking callbacks (also known as
synchronous callbacks or just callbacks) and deferred callbacks (also
known as an asynchronous callbacks). They are differ in how they control
data flow at runtime. Blocking callbacks are invoked before a function
returns, deferred callbacks may be invoked after a function returns.

Deferred callbacks are often used in the context of I/O operations or


event handling. While deferred callbacks imply the existence of multiple
threads, blocking callbacks often (but not always) rely on single thread.

Application: Callbacks are used to program applications in windowing


systems.
It is also used in the error signaling.
Callbacks can be used when communicating between processes or threads,or
through serialized communications & tabular data.
In C, the callback is implemented by using function pointer.

What is deadlock?
A deadlock is a situation in which two or more competing actions are each
waiting for the other to finish & thus neither ever does.Deadlock is a
cyclic wait among a set of processes.
In an OS, a deadlock is a situation which occurs when a process or thread
enters a waiting state because a resource requested by it is being held
by another waiting process, which in turn is waiting for another
resource. If a process is unable to change its state indefinitely because
the resources requested by it are being used by another waiting process,
then the system is said to be in deadlock.
Deadlock is a common problem in multiprocessing system, parallel
computing & distributed system, where software & hardware locks are used
to handle shared resources & implement process synchronization.

What are the necessary conditions for the deadlock?


A deadlock situation can arise if all of the following conditions hold
simultaneously in a system-
1- Mutual Exclusion- At least one resource must be held in a non-
shareable mode. Only one process can use the resource at any given
instant of time.
2- Hold & Wait or Resource Holding – A process is holding at least one
resource & requesting additional resources which are being held by
other processes.
3- No Preemption – The OS must not de-allocate resources once they
have allocated, they must be released by the holding process
voluntarily.
4- Circular wait – A process must be waiting for a resource which is
being held by another process, which in turn is waiting for the
first process to release the resource. In general, there is a set
of n waiting processes, P={P1,P2,P3,…,Pn},such that P1 is waiting
for the resource held by P2,& P2 is waiting for the resource held
by P3, & so on until the Pn is waiting for the resource held by P1.

These 4 conditions are known as Coffman Conditions.

How we can prevent the deadlock?


By avoiding any of the above condition you can avoid deadlock.

What is reentrant function?


A computer program or subroutine is called reentrant if it can be
interrupted in the middle of its execution & then safely called again
(“re-entered”) before its previous invocations complete execution. The
interruption could be caused by an internal action such as a jump or
call, or by an external action such as hardware interrupt or signal. Once
the re-entered invocation completes, the previous invocations will resume
correct execution.

What are the main properties of CAN?


From E:\Projects\Arindam\CAN\AN713 - Controller Area Network (CAN) Basics
(record it)
& diary

V.5: What is the benefit of using #defineto declare a constant?


Answer:

V.6: What is the benefit of using enumto declare a constant?


Answer:
Using the enumkeyword to define a constant can have several benefits.
First, constants declared with enum are automatically generated by the
compiler, thereby relieving the programmer of manually assigning unique
values to each constant. Also, constants declared with enumtend to be
more readable to the programmer, because there is usually an enumerated
type identifier associated with the constant’s definition.
Additionally, enumerated constants can usually be inspected during a
debugging session. This can be an enormous benefit, especially when the
alternative is having to manually look up the constant’s value in a
header file. Unfortunately, using the enummethod of declaring constants
takes up slightly more memory space than using the #definemethod of
declaring constants, because a memory location must be set up to store
the constant.Here is an example of an enumerated constant used for
tracking errors in your program:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
}

VI.1: What is the difference between a string copy (strcpy) and a memory
copy (memcpy)? When should each be used?
Answer:
The strcpy()function is designed to work exclusively with strings. It
copies each byte of the source string to the destination string and stops
when the terminating null character(\0) has been moved. On the other
hand, the memcpy()function is designed to work with any type of data.
Because not all data ends with a null character, you must provide the
memcpy()function with the numberof bytes you want to copy from the source
to the destination. The following program shows examples of boththe
strcpy()and the memcpy()functions:

#include <stdio.h>
#include <string.h>
typedef struct cust_str {
int id;
char last_name[20];
char first_name[15];
} CUSTREC;
void main(void);
void main(void)
{
char* src_string = “This is the source string”;
char dest_string[50];
CUSTRECsrc_cust;
CUSTRECdest_cust;
printf(“Hello! I’m going to copy src_string into dest_string!\n”);
/* Copy src_string into dest_string. Notice that the destination
string is the first argument. Notice also that the strcpy()
function returns a pointer to the destination string. */
printf(“Done! dest_string is: %s\n”,
strcpy(dest_string, src_string));
printf(“Encore! Let’s copy one CUSTREC to another.\n”);
printf(“I’ll copy src_cust into dest_cust.\n”);
/* First, initialize the src_cust data members. */
src_cust.id = 1;
strcpy(src_cust.last_name, “Strahan”);
strcpy(src_cust.first_name, “Troy”);
/* Now, use the memcpy() function to copy the src_cust structure to
the dest_cust structure. Notice that, just as with strcpy(), the
destination comes first. */
memcpy(&dest_cust, &src_cust, sizeof(CUSTREC));
printf(“Done! I just copied customer number #%d (%s %s).”,
dest_cust.id, dest_cust.first_name, dest_cust.last_name);
}
When dealing with strings, you generally should use the strcpy()function,
because it is easier to use with strings. When dealing with abstract data
other than strings (such as structures), you should use the memcpy()
function.

VII.23: What is the difference between NULLand NUL?


Answer:
NULL is a macro defined in <stddef.h>for the null pointer.
NULis the name of the first character in the ASCII character set. It
corresponds to a zero value. There’s no standard macro NULin C, but some
people like to define it.

VII.20: What is the stack?


Answer:

VII.21: What is the heap?


Answer:

VII.24: What is a “null pointer assignment” error? What are bus errors,
memory faults, and core dumps?
Answer:

VII.25: How can you determine the size of an allocated portion of memory?
Answer:
You can’t

VII.26: How does free()know how much memory to release?

VIII.7: Is it possible to execute code even after the program exits the
main()function?

IX.9: What is the difference between a string and an array?

X.2: What is meant by “bit masking”?


Answer:

You might also like