38
1. Compare arrays and pointers {Give both similarities and difference}. Answer: Array is nothing but a pointer in disguise. Array name stores base address of array. Thus we can say array points to a memory location of fixed size of a particular data type. arr[1] is same as *(arr+1) {In fact 1[arr] is same as arr[1] because they both are converted into *(1+arr) and *(arr+1)} However array is not same as pointer. We may make a pointer point to an arbitrary location however an array always points to a constant memory location. Eg. int a[5]={1,2,3,4,5}; int *p=a; =>p=&a[2]; or p++; are both correct but similar statements for array 'a' will invoke error. 2. What value is assigned to the below variables? int X1 = 13/3; int X2 = 13%3; Answer: The value of X1 is 4 The value of X2 is 1

c Interiew Questions With Answers

Embed Size (px)

DESCRIPTION

C interview questions and answers

Citation preview

Page 1: c Interiew Questions With Answers

1. Compare arrays and pointers {Give both similarities and difference}.

Answer: Array is nothing but a pointer in disguise. Array name stores base address of array.

Thus we can say array points to a memory location of fixed size of a particular data type.

arr[1] is same as *(arr+1)

{In fact 1[arr] is same as arr[1] because they both are converted into *(1+arr) and *(arr+1)}

However array is not same as pointer. We may make a pointer point to an arbitrary location

however an array always points to a constant memory location.

Eg.

int a[5]={1,2,3,4,5};

int *p=a;

=>p=&a[2]; or p++; are both correct but similar statements for array 'a' will invoke error.

2. What value is assigned to the below variables?

int X1 = 13/3;

int X2 = 13%3;

Answer: 

The value of X1 is 4

The value of X2 is 1

3. What is the difference between auto variable and register variable in C?

Answer: Storage class of all variables are auto by default unless we specify a variable is register

or static or extern in C program.

Both auto variable and register variable are local variables. Register variables are stored

in register memory. Whereas, auto variables are stored in main CPU memory.

Register variables will be accessed very faster than the normal/auto variables since they

are stored in register memory rather than main memory.

But, only limited variables can be used as register since register size is very low. (16 bits,

32 bits or 64 bits)

4. What is the difference between auto variable and static variable in C?

Answer: 

Page 2: c Interiew Questions With Answers

Both auto and static variables are local variables.

Static variables can retain the value of the variable between different function calls.

But, scope of auto variable is within the function only. It can’t retain the value of the

variable between different function calls.

5. Find output of following C code:

char *getString()

{

    char str[] = "Will I be printed?";   

    return str;

}

int main()

{

    printf("%s", getString());

    getchar();

}

Output: Some garbage value

The above program doesn't work because array variables are stored in Stack Section and

have a definite lifetime. So, when getString returns, value at str are deleted and str becomes

<dangling pointer>.

6. How do you access the values within an array?

Answer: Arrays contain a number of elements, depending on the size you gave it during variable

declaration. Each element is assigned a number from 0 to number of elements-1. To assign or

retrieve the value of a particular element, refer to the element number. For example: if you have

a declaration that says “intscores[5];”, then you have 5 accessible elements, namely: scores[0],

scores[1], scores[2], scores[3] and scores[4].

7.  Can I use  “int” data type to store the value 32768? Why?

Page 3: c Interiew Questions With Answers

Answer: No. “int” data type is capable of storing values from -32768 to 32767. To store 32768,

you can use “long int” instead. You can also use “unsigned int”, assuming you don’t intend to

store negative values.

8. What are multidimensional arrays?

Answer: Multidimensional arrays are capable of storing data in a two or more dimensional

structure. For example, you can use a 2 dimensional array to store the current position of pieces

in a chess game, or position of players in a tic-tac-toe program.

9. What is the difference between Call by Value and Call by Reference?

Answer: When using Call by Value, you are sending the value of a variable as parameter to a

function, whereas Call by Reference sends the address of the variable. Also, under Call by

Value, the value in the parameter is not affected by whatever operation that takes place, while in

the case of Call by Reference, values can be affected by the process within the function.

10. What is the difference between functions getch() and getche()?

Answer: Both functions will accept a character input value from the user. When using getch(),

the key that was pressed will not appear on the screen, and is automatically captured and

assigned to a variable. When using getche(), the key that was pressed by the user will appear on

the screen, while at the same time being assigned to a variable. 

11. What is the difference between actual and formal parameters?

Answer: The parameters sent to the function at calling end are called as actual parameters while

at the receiving of the function definition called as formal parameters.

12. Can a program be compiled without main() function?

Answer: Yes, it can be but cannot be executed, as the execution requires main() function

definition.

13. What are pointers?

Page 4: c Interiew Questions With Answers

Answer: Pointers point to specific areas in the memory. Pointers contain the address of a

variable, which in turn may contain a value or even an address to another memory.

14. What is NULL pointer? 

Answer: NULL is used to indicate that the pointer doesn’t point to a valid location. Ideally,

we should initialize pointers as NULL if we don’t know their value at the time of

declaration. Also, we should make a pointer NULL when memory pointed by it is

deallocated in the middle of a program.

15. What is Dangling pointer?

Answer: Dangling Pointer is a pointer that doesn’t point to a valid memory location.

Dangling pointers arise when an object is deleted or deallocated, without modifying the

value of the pointer, so that the pointer still points to the memory location of the deallocated

memory. Following are examples.

16. What is the advantage of declaring void pointers?

Answer: When we do not know what type of the memory address the pointer variable is going

to hold, then we declare a void pointer for such.

17. Can a pointer access the array?

Answer: Pointer by holding array’s base address can access the array.

18. What will be the output?

char str[] = "Hello World";

long *ptr = (long*)str;

ptr++;

printf("%s", ptr);

Output:"o World"

Long pointer increment by one increases the value of the pointer by 4 bytes. Initially the pointer

was at &str[0]. After increment, the pointer will be at &str[4].

Page 5: c Interiew Questions With Answers

19. What is a self-referential structure?

Answer: A structure containing the same structure pointer variable as its element is called as

self-referential structure.

20. Can you pass an entire structure to functions?

Answer: Yes, it is possible to pass an entire structure to a function in a call by method style.

However, some programmers prefer declaring the structure globally, then pass a variable of that

structure type to a function. This method helps maintain consistency and uniformity in terms of

argument type.

21. What will be output of following c code?

void main()

{

struct employee

{

unsigned id: 8;

unsigned sex:1;

unsigned age:7;

};

struct employee emp1={203,1,23};

clrscr();

printf("%d\t%d\t%d",emp1.id,emp1.sex,emp1.age);

getch();

}

Output: 203 1 23

22. What is the difference between "printf(...)" and "sprintf(...)"?

Answer: the printf() function is supposed to print the output to stdout.In sprintf() function we

store the formatted o/p on a string buffer.

Page 6: c Interiew Questions With Answers

the printf() function is supposed to print the output to stdout.In sprintf() function we store the

formatted o/p on a string buffer.

the printf() function is supposed to print the output to stdout.In sprintf() function we store the

formatted o/p on a string buffer.

23. What is the difference between "calloc(...)" and "malloc(...)"?

Answer: Some important distance between calloc and malloc are given below:

 malloc:

 malloc takes only the "size" of the memory block to be allocated as input parameter.

malloc allocates memory as a single contiguous block.

if  a single contiguous block cannot be allocated then malloc would fail.

calloc:

calloc takes two parameters: the number of memory blocks and the size of each block of memory

calloc allocates memory which may/may not be contiguous.

all the memory blocks are initialized to 0.

it follows from point 2 that, calloc will not fail if memory can beallocated in non-contiguous

blocks when a single contiguous blockcannot be allocated.

24. What is the difference between String and Array?

Answer: Main difference between String and Arrays are:

A string is a specific kind of an array with a well-known convention to determine its length

where as An array is an array of anything.

In C, a string is just an array of characters (type char)and always ends with a NULL character.

The �value� of an array is the same as the address of (or a pointer to) the

first element; so, frequently, a C string and a pointer to char are used to mean the same thing.

An array can be any length. If it�s passed to a function, there�s no way the function can tell

how long the array is supposed to be, unless some convention is used. The convention for strings

is NULL termination; the last character is an ASCII NULL character.

Array can hold group of element of the same the type, and which allocates the memeory for each

element in the array,if we want we can obtain the particular value from an array by giving index

value.

Page 7: c Interiew Questions With Answers

Ex: int a[10];

a variable holds the values of integer at max 10.

String can hold any type of data, but it makes together we can't obtain the particular value of the

string.

String s="Pra12";

25. What is a modulus operator?

Answer: it gives reminder of any division operation

It is an binary arithmetic operator which returns the remainder of division operation. It can used

in both floating-point values and integer values.

Use of the modulus operator is given below:

opLeft % opRight

where, opLeft is the left operand and opRight is the right operand. This expression is equivalent

to the expression opLeft - ((int) (opLeft / opRight) * opRight)

in c language it is used to determine the remainder of any no by deviding the operator if both of

them is not float no.

it gives remainder part of divisoneg. printf("%d",5%2) output 1

26. Which one is faster n++ or n+1?Why??

Answer: The expression n++ requires a single machine instruction. n+1 requires more

instructions to carry out this operation.

27. Diffenentiate between an internal static and external static variable?

Answer: Some main difference between internal static and external static are given below:

We declare the internal static variable inside a block with static storage class. External static

variable is declared outside all the blocks in a file.

In internal static variable has persistent storage,no linkage and block scope, where as in external

static variable has permanent storage,internal linkage and file scope.

28.What are the characteristics of arrays in C?

Answer: some main characteristics of arrays are given below:

Page 8: c Interiew Questions With Answers

1.all entry in array should have same data type.

2.tables can store values of difference datatypes.

29. What is an argument ? differentiate between formal arguments and actual arguments?

Answer: Using argument we can pass the data from calling function to the called function.

Arguments available in the funtion definition are called formal arguments. Can be preceded by

their own data types.

We use Actual arguments in the function call.

30. What is the purpose of main( ) function?

Answer: Main function is to be called when the program getting started.

1.It is the first started function.

2.Returns integer value.

3.Recursive call is allowed for main() also.

4.it is user-defined function

5.It has two arguments:

5.1)argument count

5.2) argument vector(strings passed)

6.We can use any user defined name as parameters for main(),behalf of argc and argv.

31. What are the advantages of the functions?

Answer: Some main advantages of the functions are given below:

1.It makes Debugging easier.

2.Using this we can easily understand the programs logic.

3.It makes testing easier.

4.It makes recursive calls possible.

5.These are helpful in generating the programs.

32. What is a pointer variable?

Answer: A pointer variable is used to contain the address of another variable in the memory.

Page 9: c Interiew Questions With Answers

33. What is a pointer value and address?

Answer: It is a data object,it refers to a memory location.we numbered every memory locaion in

the memory.

Numbers that we attached to a memory location is called the address of the location.

34. How are pointer variables initialized?

Answer: We can initialize the Pointer variables by using one of the two ways which are given

below:

1.Static memory allocation

2.Dynamic memory allocation

35. What is static memory allocation and dynamic memory allocation?

Answer: Information regarding static men\mory allaocaion and dynamic memory allocation are

given below:

Static memory allocation:

The compiler allocates the required memory space for a declared variable.Using the address of

operator,the reserved address is obtained and assigned to a pointer variable.most of the declared

variable have static memory,this way is called as static memory allocation.

In tis memory is assign during compile time.

Dynamic memory allocation:

For getting memory dynamically It uses functions such as malloc( ) or calloc( ).the values

returned by these functions are assingned to pointer variables,This way is called as dynamic

memory allocation.

In this memory is assined during run time.

36. What is the purpose of realloc( )?

Answer: Realloc(ptr,n) function uses two arguments.

The first argument ptr is a pointer to a block of memory for which the size is to be altered.

The second argument n specifies the new size.The size may be increased or decreased.

37. What is difference between static and global static variable?

Page 10: c Interiew Questions With Answers

Answer: Main difference between static and global static variables are given below:

In context of memory it allocated to static variables only once.

Static global variable has scope only in the file in which they are declared. outside the file it can

not be accessed. but its value remains intact if code is running in some other file

38. What are advantages and disadvantages of external storage class?

Answer: Some main advantages and disadvantages of external storage class are given below:

advantage:

1.In Persistent storage of a variable retains the updated value.

2.The value is globally available.

Disadvantage:

1. Even we does not need the variable the storage for an external variable exists.

2.Side effect may be produce unexpected output.

3.We can not modify the program easily.

39. How can we read/write structures from/to data files?

Answer: There 2 function given in C++. They are fread() & fwrite(). Using them we can read &

write structures from/to data files respectively.

Basic representation:

fread(&structure, sizeof structure,1,fp);

fread function recieves a pointer to structure and reads the image(memory) of the structure as a

stream of bytes. Sizeof gives the bytes which was occupied by structure.

fwrite(&structure, sizeof structure,1,fp);

fwrite function recieves a pointer to structure and writes the image(memory) of the structure as a

stream of bytes. Sizeof gives the bytes which was occupied by structure.

40. How to add 2 numbers without + sign?

Answer: I have given you some examples.Which add 2 numbers with using + sign.

Using recursion:

#include

Page 11: c Interiew Questions With Answers

int add(int m, int n)

{

if (!m)

return n;

else

return add((m & n) << 1, m ^ n);

}

int main()

{

int m,n;

printf("Enter the 2 numbers: \n");

scanf("%d",&m);

scanf("%d",&n);

printf("Addition is: %d",add(m,n));

}

m ^ n is mandatry in addition of bits, "(a & b) << 1" is the overflow.

Using Binary operator:

1 = 001

2 = 010

add(001, 010) => a -> 001, b-> 010

=011

41. What is the difference between compile time error and run time error?

Answer: Some main differences between compiler time error and run time error are given below:

1.Compile time error are semantic and syntax error. Where Run time error are memory

allocation error e.g. segmentation fault.

2.Compile time errors comes because of improper Syntax.Where In java Run time Errors are

considered as Exceptions.Run time errors are logical errors.

3.Compile time errors are handled by compiler. where Run time errors are handled by

programmers.

Page 12: c Interiew Questions With Answers

42. Are the variables argc and argv are local to main()?

Answer: Yes,argc and argv variables are local to main().Because write any thing b/w parenthesis

is work as local to that method.

43. What are enumerations?

Answer: Enumeration is a kind of type.It is used to hold the group of constt values that are given

by programmer.After defining we can use it like integer type.e.g.

enum off,on;

Here,off and on are 2 integer constants.These are called enumerators.By default value assign to

enumurator are off.

44. What is the difference between #include <file> and #include ?file?

Answer: In C we can include file in program using 2 type:

1.#include

2.#include?file?

1.#include:In this which file we want to include surrouded by angled brakets(< >).In this method

preprocessor directory search the file in the predefined default location.For instance,we have

given include variable

INCLUDE=C:COMPILERINCLUDE;S:SOURCEHEADERS;

In this compiler first checks the C:COMPILERINCLUDE directory for given file.When there it

is not found compiler checked the S:SOURCEHEADERS directory.If file is not found there also

than it checked the current directory.

#include method is used to include STANDARDHEADERS, like:stdio.h,stdlib.h.

2.#include?file?:In this which file we want to include surrouded by quotation marks(" ").In this

method preprocessor directory search the file in the current location.For instance,we have given

include variable

INCLUDE=C:COMPILERINCLUDE;S:SOURCEHEADERS;

In this compiler first checks the current directory.If there it is not found than it checks

C:COMPILERINCLUDE directory for given file.When there it is not found compiler,than

checked the S:SOURCEHEADERS directory.

Page 13: c Interiew Questions With Answers

#include?file?method is used to include NON-STANDARDHEADERS.These are those header

files that created by programmers for use .

45. Difference between malloc and calloc?

Answer: Some main and important difference b/n malloc and calloc are given below:

malloc is use for memory allocation and initialize garbage values. where as calloc is same as

malloc but it initialize 0 value.

example:

// This allocats 200 ints, it doesn't initialize the memory:

int *m = malloc(200*sizeof(int));

// This, too, allocates 200 ints, but initializes the memory

// to zero:

int *c = calloc(200,sizeof(int));

46. Can we execute printf statement without using semicolan?

Answer: Yes,We can execute printf statement without using semicolan. When we write printf

inside the if,for,while,do while etc it gives output.

Example:

void main()

{

if(printf("R4R Welcomes you!"))

{

/*statements*/

}

}

void main()

{

while(printf("Welcome"))

{

/*statements*/

Page 14: c Interiew Questions With Answers

}

}

47. Is C is platform dependent or independent?how and why?

Answer: Major issue behind designing C language is that it is a small,portable programming

language. It is used to implement an operating system.In past time C is a powerful tool for

writing all types of program and has mechanism to achieve all most programming goals.So, we

can say that C is platform dependent.

49. how to switch the values of two variable without using third variable?

Answer: I have given a example which switch the values of two variables without using third

variable.

#include

void main()

{

int val1,val2;

val1=5;

val2=6;

/* now adding val2 to val1 we have */;

val1=val2+val1;

val2=val1-val2;

/* now here val2 will get value of val1 */;

val1=val1-val2

/*this will give val1 value of val2 */;

}

50. Explain about storage of union elements.

Answer: The key point about storage of union elements is that Union elements are use to share

common memory space.

Page 15: c Interiew Questions With Answers

51. What are header files?Can i run program without using header file?

Answer: Basically header files are the library functions.Header files have definitions of

functions.These are required to execute the specific operation of function.we write header file

with .h extension.Generally these are pre-defined fuctions,But we can also generate

our own header file.

Example:

stdio.h header file is use to perform function like prinf and scanf.

conio.h header file is use to perform function like clrscr and getch.

52. What is macro?

Answer: Macros are the fragment of code.That are used to given a name.When we want to used

thew name it is being replaced by content of macros.we can differentiate macros in terms of what

they look like & when they are used.Macros are of two types:

1.Object-like macros.

2.Function-like macros.

When we used Object-like macros It resembles data objects.Where as when we using

function-like macros it resembles function calls.

53. What is the difference between getch() and getchar()?

Answer: Key difference b/n getch() and getchar() are given below:

getch() read the key hits without waiting you to press enter.Where as getchar() does not read key

hits and wait till you press enter.

54. What does exit() do?

Answer: It is used to comes out of execution normally.

55. What is an volatile variable?

Answer: We can not modify the variable which is declare to volatile during execution of whole

program.

Page 16: c Interiew Questions With Answers

Example:

volatile int i = 10;

value of i can not be changed at run time.

56. How to access or modify the constt variable in C ?

Answer: We can not modify the constant variable.

57. What do you understand about datatype?

Answer: C Language has supported many data types.Which we use writing program.C Language

gave authority to programmers to create and use datatypes.

Below i have shown you list of basic data types.That are introduce by ANSI standard.

datatypes in C:

char: required 1 byte and it used for characters or integer variables.

int: required 2 or 4 bytes and it used for integer values.

float: required 4 bytes and it used for Floating-point numbers.

double: required 8 bytes and it used for Floating-point numbers.

58. How to define their types of variables and initialize them?

Answer: Variables are made by programmers.It can be modified.When we defined any data

object as a singular variable can be defined also as an array.

In C variable are of many type. Like: an integer or character, or may be of compound data

objects(Like: structure or unions).

Initialization of variable:

int num; //Here we declare num variable as integer and it is initialized as default size.

int num=0; //Here we declare num variable and initialize them with 0.

59. What are the Array?How to define and declare them?

Answer: Basically Array are the collection of same data type.It has common name and addressed

as a group.

Declaration of an Array:

We have to declare Array also as a single data object.

Page 17: c Interiew Questions With Answers

int Array[10];

In this array of integers are created.Than first member in the array are addressed as Array[0] and

last member has been declared as Array[9].

Example:

#define MAX_SIZE 10

int Array[MAX_SIZE];

int n;

for (n = 1; n <= MAX_SIZE; n++)

{

Array[n] = n;

}

Definition of an Array:

We know that we declare an array like that,

int Array[10];

When an array is external, it must be defined

in any other source files that may need to access it. Because you don�t want the compiler

to reallocate the storage for an array, you must tell the compiler that the array is allocated

externally and that you want only to access the array.

60. What are the pointers?How to declare them?

Answer: Pointers are may be of variable or constant.The contains the address of object.Some

important characteristics of pointers are given below:

1.Pointer is used to contain the address of any object.It may be an array,a singular variable,a

union and a structure.

2.It is also used to store the address of a function.

3.It can not hold the address of the constant.

Remember that when a pointer getting incremented than its value is incremented by the sizeof()

the pointer's type.

We can declare and initialize the pointer like that:

int counter= 0;

Page 18: c Interiew Questions With Answers

int *pcounter;

pcounter = &counter;

61. What are the Bit Operators?

Answer: Bit operators are different frm logical operator. So,don't confuse with them.The

keyword TRUE signifies a true bit (or bits) that is set to one,

and FALSE signifies a bit (or bits) that is set to zero.

Some Bitwise Operators are given below:

&: Performs a bitwise AND operation. If both operands are TRUE, the result is TRUE;

otherwise, the result is FALSE.

|: Performs a bitwise OR operation. If either operand is TRUE, the result is TRUE; otherwise, the

result is FALSE.

^: Performs a bitwise exclusive OR operation. If both operands are TRUE or both operands are

FALSE, the result is FALSE. The result is TRUE if one operand is TRUE and the other is

FALSE. Exclusive OR is used to test to see that two operands are different.

<<: Shifts the X operand, Y operand bits to the left. For example, (1 << 4) returns a value of 8. In

bits, (0001 << 4) results in 1000. New

positions to the left are filled with zeroes. This is a quick way to multiply by 2, 4, 8, and so on.

>>: Shifts the X operand, Y operand bits to the right. For example, (8

>> 4) returns a value of 1. In bits, (1000 >> 4) results in 0001. New positions to the right are

filled with ones or zeroes, depending on the value and whether the operand being shifted is

signed. This is a quick way to divide by 2, 4, 8, and so on.

// Using a bitwise AND:

if (x & y)

{

// With x == 1, and y == 2, this will NEVER be TRUE.

}

62. How to use free() function?

Answer: Free() function is used to return the memory to the operating system after use.Because

is most of time very limited source.So,we have to try to made max output.

Page 19: c Interiew Questions With Answers

Example:

#include

#include

int main ()

{

int *R1, *R2, *R3;

R1 = (int*) malloc (10*sizeof(int));

R2 = (int*) calloc (10,sizeof(int));

R3 = (int*) realloc (R2,50*sizeof(int));

free (R1);

free (R3);

return 0;

}

63. How to differentiate local memory and global memory?

Answer: Local and global memory allocation is applicable with Intel 80x86 CPUs.

Some main difference b/n local and global variables are given below:

1.Using local memory allocation we can access the data of the default memory segment,Where

as with global memory allocation we can access the default data,located outside the

segment,usually in its own segment.

2.If our program is a small or medium model program , the default memory pool is local,Where

as If our program uses the large or compact memory model, the default memory pool is global.

64. What are the Text Files and Binary Files?

Answer: Text Files: Text Files are those files that are display on the screen.These files are

readable files.It has not uses only few special characters like,tab and newlines.Text Files

generally introduce by programmers.

Binary Files: Binary Files are those files that can contain any data, including the internal

representation of numbers, special control characters.

65. What is a data type?

Page 20: c Interiew Questions With Answers

Answer: It is means to identify type of data. When we are storing something in our program

then we need to allocate some space for that purpose and while allocating that

space we must also specify what kind of data is to be stored in the

allocated space.

Data types help to solve this problem.

66. Give example of some data types?

Answer: Int, char, float, void etc. are all examples of predefined basic primitive data types.

Structures and Unions are user defined data types.

67. Is it possible to bring about conversion from one data type to other?

Answer: Yes, most programming languages provide ways for data to be converted from one data

type to other. Data conversion can be both implicit and explicit. Implicit type conversion

involves automatic type promotion. Explicit type conversion is also called type casting and may

lead to loss in data precision.

68. What is the meaning of prototype of a function?

Answer: Prototype of a function

Declaration of function is known as prototype of a function. Prototype of a function means

(1) What is return type of function?

(2) What parameters are we passing?

(3) For example prototype of printf function is:

int printf(const char *, …);

I.e. its return type is int data type, its first parameter constant character pointer and second

parameter is ellipsis i.e. variable number of arguments.

69. What is size of void pointer? 

Answer: Size of any type of pointer in c is independent of data type which is pointer is pointing

i.e. size of all type of pointer (near) in c is two byte either it is char pointer, double pointer,

Page 21: c Interiew Questions With Answers

function pointer or null pointer.  Void pointer is not exception of this rule and size of void

pointer is also two byte.

70. What will be the output of the following code?

 void main ()

      {      int i = 0 , a[3] ;

      a[i] = i++;

      printf (“%d",a[i]) ;

      }

Answer: The output for the above code would be a garbage value. In the statement a[i] = i++; the

value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get

incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value.

71. Why doesn't the following code give the desired result?

 ANSWER: int x = 3000, y = 2000 ;

      long int z = x * y ;

      Answer: Here the multiplication is carried out between two ints x and y, and  the result that

would overflow would be truncated before being assigned to  the variable z of type long int.

However, to get the correct output, we should use an explicit cast to force long arithmetic as

shown below:

      long int z = ( long int ) x * y ;

      Note that ( long int )( x * y ) would not give the desired effect. 

72. Why doesn't the following statement work?

ANSWER:      char str[ ] = "Hello" ;

                        strcat ( str, '!' ) ;

  Answer: The string function strcat( ) concatenates strings and not a character. The basic

difference between a string and a character is that a string is a collection of characters,

represented by an array of characters whereas a character is a single character. To make the

above statement work writes the statement as shown below:

                        strcat ( str, "!" ) ; 

73. How do I know how many elements an array can hold?

Page 22: c Interiew Questions With Answers

ANSWER: The amount of memory an array can consume depends on the data type of an array.

In DOS environment, the amount of memory an array can consume depends on the current

memory model (i.e. Tiny, Small, Large, Huge, etc.). In general an array cannot consume more

than 64 kb. Consider following program, which shows the maximum number of elements an

array of type int, float and char can have in case of Small memory model.

                              main( )

                              {

                              int i[32767] ;

                              float f[16383] ;

                              char s[65535] ;

                              }

74. How do I write code that reads data at memory location specified by segment and offset?

ANSWER: Use peekb( ) function. This function returns byte(s) read from specific segment and

offset locations in memory. The following program illustrates use of this function. In this

program from VDU memory we have read characters and its attributes of the first row. The

information stored in file is then further read and displayed using peek( ) function.

#include

#include

main( )

{

char far *scr = 0xB8000000 ;

FILE *fp ;

int offset ;

char ch ;

if ( ( fp = fopen ( "scr.dat", "wb" ) ) == NULL )

{

printf ( "\nUnable to open file" ) ;

exit( ) ;

}

// reads and writes to file

for ( offset = 0 ; offset < 160 ; offset++ )

Page 23: c Interiew Questions With Answers

fprintf ( fp, "%c", peekb ( scr, offset ) ) ;

fclose ( fp ) ;

if ( ( fp = fopen ( "scr.dat", "rb" ) ) == NULL )

{

printf ( "\nUnable to open file" ) ;

exit( ) ;

}

// reads and writes to file

for ( offset = 0 ; offset < 160 ; offset++ )

{

fscanf ( fp, "%c", &ch ) ;

printf ( "%c", ch ) ;

}

fclose ( fp ) ;

}

75. What is C language?

ANSWER: The C programming language is a standardized programming language developed in

the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It

has since spread to many other operating systems, and is one of the most widely used

programming languages. C is prized for its efficiency, and is the most popular programming

language for writing system software, though it is also used for writing applications.

76. Inprintf() Function What is the output of printf("%d")?

ANSWER: 1. When we write printf("%d",x); this means compiler will print the value of x. But

as here, there is nothing after �%d� so compiler will show in output window garbage value.

2. When we use %d the compiler internally uses it to access theargument in the stack

(argument stack). Ideally compiler determines the offset of the data variable depending on the

format specification string. Now when we write printf("%d",a) then compiler first accesses the

top most element in the argument stack of the printf which is %d and depending on the

Page 24: c Interiew Questions With Answers

format string it calculated to offset to the actual datavariable in the memory which is to be

printed. Now when only %d will be present in the printf then compiler will calculate the correct

offset (which will be the offset to access the integer variable) but as the actual data object is to be

printed is not present at that memory location so it will print what ever will be the contents of

that memory location.

3. Some compilers check the format string and will generate an error without the proper number

and type of arguments for things like printf(...) and scanf(...).

77. malloc() Function- What is the difference between "calloc(...)" and "malloc(...)"?

ANSWER: 1. calloc(...) allocates a block of memory for an array of elements of a certain size.

By default the block is initialized to 0. The total number of memory allocated will be

(number_of_elements * size).

malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...)

allocated bytes of memory and not blocks of memory like calloc(...).

2. malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL

if there is insufficient memory available.

calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the

allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to

set the new handler mode.

78. In printf() Function- What is the difference between "printf(...)" and "sprintf(...)"?

ANSWER: sprintf(...) writes data to the character array whereas printf(...) writes data to the

standard output device.

79. Compilation How to reduce a final size of executable?

ANSWER: Size of the final executable can be reduced using dynamic linking for libraries.

Page 25: c Interiew Questions With Answers

80. Linked Lists -- Can you tell me how to check whether a linked list is circular?

ANSWER: Create two pointers, and set both 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");

}

}

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, its either 1 or 2 jumps until they meet.

81. string Processing --- 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.

ANSWER: void PrintPermu (char *sBegin, char* sRest) {

int iLoop;

char cTmp;

char cFLetter[1];

char *sNewBegin;

char *sCur;

int iLen;

static int iCount;

iLen = strlen(sRest);

if (iLen == 2) {

iCount++;

printf("%d: %s%s\n",iCount,sBegin,sRest);

iCount++;

 

Page 26: c Interiew Questions With Answers

printf("%d: %s%c%c\n",iCount,sBegin,sRest[1],sRest[0]);

return;

} else if (iLen == 1) {

iCount++;

printf("%d: %s%s\n", iCount, sBegin, sRest);

return;

} else {

// swap the first character of sRest with each of

// the remaining chars recursively call debug print

sCur = (char*)malloc(iLen);

sNewBegin = (char*)malloc(iLen);

for (iLoop = 0; iLoop <>

strcpy(sCur, sRest);

strcpy(sNewBegin, sBegin);

cTmp = sCur[iLoop];

sCur[iLoop] = sCur[0];

sCur[0] = cTmp;

sprintf(cFLetter, "%c", sCur[0]);

strcat(sNewBegin, cFLetter);

debugprint(sNewBegin, sCur+1);

}

}

}

void main() {

char s[255];

char sIn[255];

printf("\nEnter a string:");

scanf("%s%*c",sIn);

memset(s,0,255);

PrintPermu(s, sIn);

}