c interview qes & ans

Upload: victor-othugadi

Post on 07-Apr-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 c interview qes & ans...

    1/15

    C INTERVIEW QUESTIONS WITH ANSWERS.Q: What does static variable mean?A: They are stored in memory. Default initial value is zero. Their scopeis local to the block in which the variable is defined & value of the

    variable persists between different function calls. Avoid using staticunless we need it. Because their values are kept in memory when thevariables are not active, which means they take up space in memorythat could otherwise used by other variables.Q: What is a pointer?A: Pointer is an address variable which contains address of anothervariable. Pointer operators are * and &. int pointer contains address ofint quantity, float contains float quantity, same holds good for eachdata type even for user defined data types. Maximum size of pointer is

    2 bytes.Ex of pointer declaration:int a=27;int *p;p=&a;ORint *p=&a;

    Q: What is a structure?A: A structure is a collection of one or more variables, possibly ofdifferent data types, grouped together under a single name for

    convenient handling.

    Q: What are the differences between structures and arrays?A: In array we can store variables of same data type while in structurewe can store variables of different data types. In C++ structure, wecan add function also to the structure.

    Q: In header files whether functions are declared or defined?A: Functions are declared in header files & defined in the program.This can be explained as if we use printf() without including stdio.h

    then it will show complile time error as function should have prototype.With this function prototype compiler came to know which type offunctions we r using. Thats why function prototype should be givenbefore using predefined or userdefined functions.

    Q: What are the differences between malloc() and calloc()?A: Both these functions are declared in alloc.h & are used to dynamicmemory allocation of a variable. Difference is that: malloc() takes only

  • 8/4/2019 c interview qes & ans...

    2/15

    one argument while calloc() will take two arguments. Ex: Suppose wehave to dynamically alloc memory for 10 int variables then it can bedone as:int *p=(int *)malloc(n * 2) where n=10 & 2=sizeof(int)int *p=(int *)calloc(10,2)

    Q: What are macros? What are its advantages and disadvantages?A: Macros are preprocessor directives. They get replaced in sourcecode before compilation.Advantages are:

    We can replace any valid C statement or condition in user ownwords. We can do File inclusion also. We can do conditionalcompilation. We can pass arguments also in Macros. They can beused anywhere inside the program.

    Disadvantages are: Macro will replace macro template with its macro expansion

    without checking any error. If there r number of occurrence ofmacros then it will increase the size of program.

    Q: Difference between pass by reference and pass by value?A: When we have argument as variable or any constant then functionis termed as function pass by value. When we have address of variableas an argument in the function we call the function by reference.Ex:int x=27;void func(x) pass by value

    void func(27) pass by valuevoid func(&x) pass by reference

    Q: What is static identifier?A: As explained above.

    Q: Where are the auto variables stored?A: They are stored in memory & default initial value is garbage value.

    Q: Where does global, static, local, register variables, free memory

    and C Program instructions get stored?A: Refer let us C.Q: Difference between arrays and linked list?A: Main difference is that array are static in nature. Once we declare itwe cant modify its size. Also inserting or deleting elements in array isdifficult. Array have fixed size thats why if at runtime, we want toincrease or decrease its size, is not possible. While linked list are

  • 8/4/2019 c interview qes & ans...

    3/15

    dynamic in nature they dynamically allocate memory for variables.Their size can be decided at runtime. Inserting & deleting element isalso easy. One more difference is that searching a particular elementis quite easy as it would use array index number while linked list willsearch the element from the start of list even thought the position of

    element is last. Thats why traversing takes more time.

    Q: What are enumerations?A: An enumerated data type is user defined data type which provides away for attaching name to numbers. Syntax is similar to structure. Theenum keyword automatically enumerated the list of variables byassigning value 0,1,2,3.enum shape{circle, square, rectangle)here value of circle=0, square=1, rectangle=2enum{red, green=7, blue=10};here value of red=0, green=7, blue=10We cant use float values in enum, only int values are allowed.

    Q: Describe about storage allocation and scope of global, extern,static, local and register variables?A: Refer let us C.

    Q: What are register variables? What are the advantage of usingregister variables?A: A: Refer let us C.

    Q: What is the use of typedef?A: typedef keyword is used to rename the data type.Ex: typedef int INTEGER;So instead of int a we have to use INTEGER a;

    Q: Can we specify variable field width in a scanf() format string? Ifpossible how?A: As in following code:void main(){float f;printf(Enter value of f : );scanf(%3f,&f);printf(f : %f,f);}If we enter f=12345.6789 it will give result as f=123

  • 8/4/2019 c interview qes & ans...

    4/15

    Q: Out of fgets() and gets() which function is safe to use and why?A: gets() receives a string from the keyboard. More exactly, gets()gets a new line (\n) terminated string of characters from the keyboard

    and replaces the \n with \0;Ex: char[10] s; gets(s);fgets() used to read a string from the file. fgets() takes threearguments. First is the address where the string is stored, second I themaximum length of the string which will prevent fgets() from readingin too long a string and overflowing the array. Third one is File pointer.If all lines from file have been read & we attempt to read one moreline, in that case fgets() returns null. It also retains \n at the end ofstring & appends null byte to string to mark the end of string.Syntax: fgets(char *s, int n, FILE *fp)Thats why fgets() is more safer.

    Q: Difference between strdup and strcpy?A: strcpy() is defined in string.h copies one string into another.Syntax: strcpy(char *destination, char * source);Strdup() is also defined in string.h which will copy the string to newlycreated location. In strdup() makes a duplicate of source string ,obtaining space with a call to malloc. Allocated space is (strlen(sourcestring) +1) byte. Also we have to free this string when it is not usedby calling free. Thats why we have to add alloc.h while using strdup().Ex: char *dupstr=strdup(char * sourcestr);

    Q: What is recursion?A: A function is called recursive if a statement within the body of afunction calls the same function. It is the process of definingsomething in terms of itself.

    Q: Differentiate between a for loop and a while loop? What are it uses?A: Simple Question.

    Q: What are the different storage classes in C?

    A: auto, register, static & extern are different storage classes.

    Q: Write down the equivalent pointer _expression for referring thesame element a[i][j][k][l]?A: *(*(*(*(a+i)+j)+k)+l)Q: What is difference between Structure and Unions?

  • 8/4/2019 c interview qes & ans...

    5/15

    A: Declaration syntax is same foe both difference is that structuremembers have contiguous memory location while union membersshare common memory location having the size equal to variable sizewhose size is maximum than other variables.

    Q: What the advantages of using Unions?A: Unions are very useful while interacting with the hardware of thecomputer.

    Q: What are the advantages of using pointers in a program?A: Pointers will increase the execution speed. Using pointers we canacess array as they are correlated to each other. Also pointer canreturn more than one value from function. From called function we canchange value of any variable of calling function using pointer.

    Q: What is the difference between Strings and Arrays?A: String is a character array. Array is defined as collection of similardata types under single variable name. They are also used as indexedvariables as they r accessed by their indexes.So there is no difference between string & array. As string is anothername for char array.

    Q: In a header file whether functions are declared or defined?A: Already explained.Q: How structures are passed & return from the function?

    A: Structures are user defined data types. So it is possible to passstructure as an argument or functions can return structures.Following example shows how structures are passed as an argument infunction :#include#includevoid show(struct emp);

    struct emp{

    int age;char name[20];float salary;

    }e1={21,"Himanshu",27000};

  • 8/4/2019 c interview qes & ans...

    6/15

    void main(){

    clrscr();show(e1);getch();

    }void show(struct emp e1){

    printf("Age : %d \n",e1.age);printf("Name : %s \n",e1.name);printf("Salary : %f \n",e1.salary);

    }

    Following example show how functions return the structure:

    #include#includestruct emp show();struct emp{

    int age;

    char name[20];float salary;

    };void main(){

    struct emp e1;clrscr();e1=show();clrscr();

    printf("Age : %d \n",e1.age);printf("Name : %s \n",e1.name);printf("Salary : %f \n",e1.salary);getch();

    }struct emp show(){

  • 8/4/2019 c interview qes & ans...

    7/15

    struct emp e1;printf("Enter the age : ");scanf("%d",&e1.age);printf("Enter the name : ");scanf("%s",e1.name);

    printf("Enter the salary : ");scanf("%f",&e1.salary);return e1;

    }Q: What is argc & argv?A: Command Line Argument, argc stands for argument count & argvstands for argument vector. So, c for count & v for vector.Q: How u will convert this binary digit 1101100100111100to other system & which will be easier?It is easy to convert binary number into octal number or hexadecimalnumber system. For conversion follow this number charts for octal &hexdecimal number.To convert into octal number, group the numbers from right to lefteach consisting of 3 numbers. So for given example:Binary Number: 1101100100111100Grouping: 1 101 100 100 111 100Well here the first digit is 1, so make it 001.Grouping: 001 101 100 100 111 100

    Octal conversion: 1 5 4 4 7 4So Octal conversion for 1101100100111100 = 154474Similarly for hexadecimal conversion, group the numbers from right toleft each consisting of numbers. Then follow the table.U will get as:

    1101 1001 0011 1100D 9 3 C

    So hexadecimal conversion = D93C

  • 8/4/2019 c interview qes & ans...

    8/15

    0000 0

    0001 1

    0010 2

    0011 3

    0100 4

    0101 5

    0110 60111 7

    1000 8

    1001 9

    1010 A

    1011 B

    1100 C

    1101 D

    1110 E

    1111 F

    Q: Which one is equivalent to multiplying by 2:Left shifting a numberby 1 or Left shifting an unsigned int or char by 1?A: Left shift will multiply the unsigned & int datatype. For char it willdouble the ascii value of character. E.g. left shift of A (ascii value=65)will give u character of acii value 130.Q: Are command line args are local?A: Command line arguments are local to main(). The explaination canbe given as, by default program name is the first argument, therefore

    argc cannot be less than 1, by default it is1. Though for differentprograms argc=1 by default, argv is different as explained earlier. Socommand line arguments are local to main().Q: Do structure contains pointer to itself?A: In linked list structure contain pointer to itself. Such pointers arecalled as self referential pointers.e.g

    000 0

    001 1

    010 2

    011 3

    100 4

    101 5

    110 6

    111 7

  • 8/4/2019 c interview qes & ans...

    9/15

    struct emp{

    int age;struct emp *next;

    };

    Here struct emp *next is a pointer to structure itself & it points to nextstructure element.Q: What is a far pointer? where we use it?A: A far pointer is always is treated as a 32 bit pointer & contains botha segment & an offset address.The total memory (1 mb) I divided into a number of units eachcomprising 65536 (64 kb) locations. Each such unit is called assegment. Each segment always begins at a location number, which isexactly divisible by 16. The segment register contains the addresswere a segment begins, where as the offset register contains the offsetof the data/code from where the segment begins.e.g. if segment register=2 & offset register=5 ten address ofdata/code is calculated as :(16 * 2) + 5 = 32 + 5 = 37.Declaration : char *far=0xB0008000 here segment register=0xB000 &offset register=8Generally we r using pointers are called as near pointers of 16 bits.Also 8088 b& 8086 chips (of the old PC & XT) operate only in realmode, and so can address only 1024 KB or 1MB memory. So if u want

    to use the memory beyond 64KB near pointers are not sufficient, toisolate this problem we have far & huge pointers.

    Q: How will you declare an array of three function pointers where eachfunction receives two ints andreturns a float?A: float ( * ( * arr_fptr[3])(int 1, int 2) )

    Q: What is a NULL Pointer? Whether it is same as an uninitializedpointer?

    A: For each pointer type ( like say a char pointer ) C defines a specialpointer value that is guaranteed not to point to any object or functionof that type. Usually the null pointer constant is used for representinga null pointer is the integer 0.Uninitialized pointer is not same as null pointer.

    Q: What is a NULL Macro? What is the difference between a NULLPointer and a NULL Macro?

  • 8/4/2019 c interview qes & ans...

    10/15

    A: A NULL macro is used to represent the null pointer in source code.It has a value 0 associated with it.A null pointer is a pointer, which doesnt point anywhere.The ASCII NUL character has all its bits as 0 but doesnt have anyrelationship with the null pointer.

    The null string is another name for empty string .

    Q: What does the error 'Null Pointer Assignment' mean and whatcauses this error?A: The null assignment error is generated only in small & mediummemory models which occurs when program changes the bottom ofdata segment. In Borlands C compiler, Borland places four zero bytesat the bottom of the data segment, follwed by Borlands copyrightnotice Borland C++ - Copyright Intl.. In small memory models nullpointer points to DS:0000. Thus assigning a value to the memoryreferenced by this pointer will overwrite the first zero byte in the datasegment. At the program termination, the copyright banner & fourzeroes are checked & if either has been modified, the null pointerassignment error is generated.Q: Write a program for palindrome checking?A: There r two approaches to solve this problem. First one usingfunctions available in string.h (strrev() & strcmp()) & second one iswithout using it.First approach by using strrev() & strcmp() from string.h :

    #include#include#includevoid main(){

    char *str1;char *str2;int x;

    clrscr();printf("Enter the string : ");gets(str1);str2=strrev(str1);printf("Reverse String : %s \n",str2);x=strcmp(str1,str2);if(x==0)

    printf("%s is palindrome \n",str1);

  • 8/4/2019 c interview qes & ans...

    11/15

    elseprintf("%s is not palindrome \n",str1);

    getch();}

    Second approach by using ASCII concept :#include#includevoid main(){

    char str1[20];char str2[20];int i,j;int x,y;clrscr();printf("Enter the string : ");gets(str1);for(i=0;str1[i]!='\0';i++);i--;for(j=0;i>=0;j++,i--)

    str2[j]=str1[i];str2[j]='\0';printf("Reverse string : %s \n",str2);for(i=0,j=0;str1[i]!='\0';i++,j++)

    {x=str1[i];y=str2[j];if((x-y)!=0)

    break;}if(x==y)

    printf("%s is palindrome \n",str1);else

    printf("%s is not palindrome \n",str1);

    getch();}Q: How would you dynamically allocate a one-dimensional and two-dimensional array of integers?A: Array elements have contiguous memory location. Similar holdstrue for two-dimensional array also. So there is no such arrangementthat array elements are stored in row & column in memory. Therefore

  • 8/4/2019 c interview qes & ans...

    12/15

    dynamic allocation for one-dimensional & two-dimensional array ofintegers is same. Example of dynamic allocation is in precedingquestion.Q: How can you increase the size of a dynamically allocated array?

    A:#include#include#includevoid main(){

    int i,n,*p;clrscr();printf("How many number of elements you want to enter? ");scanf("%d",&n);p=(int *)malloc(n*2);if(p==NULL){

    printf("Memory allocation unsuccessful");exit();

    }

    for(i=0;i

  • 8/4/2019 c interview qes & ans...

    13/15

    A: realloc() function used to move a particular block through n bytes.So we have to pass size of blcok & number of bytes. If block points tonull it will work same as malloc() or calloc().Q: Which function should be used to free the memory allocated by

    calloc()?A: free() from malloc.hQ: How much maximum can you allocate in a single call to malloc()?A: Not more than 64KB in small & tiny memory models.Q: How do you declare the following:A: An array of three pointers to chars=> char *arr[3]

    An array of three char pointers=> char *arr[3]A pointer to array of three chars=> char *p=&arr[3]A pointer to function which receives an int pointer and returns a floatpointer=>(float *)*funcptr(int *)A pointer to a function which receives nothing and returns nothing

    => void (*funcptr)()Q: Which header file should you include if you are to develop afunction which can accept variable number of arguments?A: We have to include stdarg.h to use va_arg(), va_list() & va_start().Which bit wise operator is suitable for putting on a particular bit in anumber?=> Bitwise AND operator is used to check whether a particular bit isON or OFF. It is also used to turn OFF a particular bit in a number.

    Q: Write a program to compare two strings without using the strcmp()function.A:#include#includevoid main()

  • 8/4/2019 c interview qes & ans...

    14/15

    {char *str1;char *str2;int x,i;clrscr();

    printf("Enter the first string : ");gets(str1);printf("Enter the second string : ");gets(str2);for(i=0;str1[i]!='\0';i++){

    x = str1[i] - str2[i];if(x!=0)

    break;}if(x==0)

    printf("Strings are equal");else

    printf("Strings are not equal");getch();

    }Q: How would you dynamically allocate a one-dimensional and two-dimensional array of integers?A: Array elements have contiguous memory location. Similar holdstrue for two-dimensional array also. So there is no such arrangement

    that array elements are stored in row & column in memory. Thereforedynamic allocation for one-dimensional & two-dimensional array ofintegers is same. Example of dynamic allocation is in precedingquestion.Q: How can you increase the size of a dynamically allocated array?A:#include#include#include

    void main(){

    int i,n,*p;clrscr();printf("How many number of elements you want to enter? ");scanf("%d",&n);p=(int *)malloc(n*2);

  • 8/4/2019 c interview qes & ans...

    15/15

    if(p==NULL){

    printf("Memory allocation unsuccessful");exit();

    }

    for(i=0;i