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

Important C Questions Pointers: 1.What is a pointer ? Ans:- Pointer is a variable which holds Address (or Reference)of an object (i.

e stores reference of an object).Object can have one or more bytes of memory. 2.Uses of pointers ? Ans:Pointers allow different sections of code to share information easily. Accessing memory belonging to one variable as a different type. Pointers provide pass by reference method for functions. Dynamic memory allocation. Dynamic data structures. Function pointer for callback functions or event handlers. 3.Difference between Call by value and call by refence? Ans:Call by Value Call by Reference In call by value, a variable is passed as an argument to a function. It creates another copy of it in memory. In this case any changes made to this variable in the child function is not refl ected back in the parent function. In call by reference, instead of the variable, its address is passed as an argument to a function. It does not creates another copy of it in memory. In this case any changes made to the value at this address in the child functi on is instantly reflected back in the parent function. 4.Equivalent pointer to a[i][j][k][l]? Ans:The equivalent pointer is *(*(*(*(a+i)+j)+k)+l). 5.Difference between pointers and arrays ? Ans:POINTERS ARRAYS Holds address of data. Data is accessed indirectly, so you first retrieve the constants of the pointer, load that as an address(call it L),then retrieve its content. If the pointer h as a subscript [i] you instead retrieve the contents of the location i units past L. Commonly used for dynamic data structures. Commonly used with malloc( ),free( ). Holds data. Data is accessed directly ,so for a[i] you simply retrieve the contents of the l ocation I units past a. Commonly used for holding a fixed number of elements of the same type of data. Implicitly allocated and deallocated.

6.What is Far pointer,near pointer and huge pointer?How many bytes are occupies

by them? Ans:--> A Near pointer is 2bytes long where as a Far and Huge pointer are 4 bytes. --> In 32 bit compiler like vc++ or gcc ,the compiler will report an error sinc e 32 bit compilers do not recognize Near,Far and Huge pointers. -->In 32 bit compilers every pointer is 4bytes wide. 7.What is NULL pointer? Is it same as an uninitialised pointer? Ans:-The constant NULL is a special pointer value which encodes the idea of poin ts to nothing. NULL is equal to the integer constant 0, so NULL can play the role of a B oolean false. Ex: char *pc=(char *)0; NULL pointer is not same as uninitialized pointer. 8.What does the error NULL pointer assignment mean? What causes this error? Ans:9.What are Dangling,Wild,Bad pointers ? Ans:Dangling pointer:-Dangling pointers arise when an object is deleted or dealloca ted ,without modifying the values of the pointers ,so that the pointer still poi nts to memory location of the deallocated memory. Always pointer must be assigned with NULL pointer after deallocat ion of memory which is referred by This pointer. Wild pointer:-Performing invalid operations are called wild pointers. This will cause segmentation faults or system crash. Process image Ex:- Valid addresses are 1000 to 1999. 1000 Int *pa=(int *)1200; //valid address. *pa=10; //valid operation. Int *pb=(int *)2005; //Invalid address. *pb=10; //Invalid operation (or) Wild pointer. 1999 Bad pointer:- pointers which are defined and are not initialized we call them a s uninitialized pointers or bad pointer. 10.What is void pointer ?What is its significance ? Ans:-Void pointer is a generic pointer , which can be assigned for any type of p ointee without using typecasting. 11.What is the difference between NULL pointer, NULL macro,the ASCII NULL character and NULL string ? Ans:- * A NULL pointer is a pointer ,which doesnt point anywhere. * A NULL macro is used to represent the null pointer in source code. It has a value zero associated with it. Syntax:- #define NULL (void *)0; * The ASCII NULL character has all its bits as 0but doesnt have any r elationship with the null pointer . * The NULL string is just another name for empty string. 12.Are the expressions *ptr++ and ++*ptr same? Ans:- No , *ptr++:- It increments the pointer. ++*ptr:- It increments the value pointed by the pointer.

13. Are the expressions (*ptr)++ and ++*ptr same? Ans:Yes. These both will increment the value pointed by the pointer. 14.what is constant qualifier ? Ans:Const qualifier qualifies variable name not memory location. Ex:- const int a=10; Int *pa=&a; *pa=20; //applicable. a=30; //Not applicable. Note :- while using const qualifier ,we must assign the value to the variable at the time of initialization itself otherwise it will take some garbage value. 15)What is a const pointer? 16)When should a type cast be used and when should it not be used?

17. How many levels of pointers can you have? The ANSI C standard says all compilers must handle at least 12 levels. Your comp iler might support more. int i = 0; int *ip01 = & i; int **ip02 = & ip01; int ***ip03 = & ip02; int ****ip04 = & ip03; int *****ip05 = & ip04; int ******ip06 = & ip05; int *******ip07 = & ip06; int ********ip08 = & ip07; int *********ip09 = & ip08; int **********ip10 = & ip09; int ***********ip11 = & ip10; int ************ip12 = & ip11; ************ip12 = 1; /* i = 1 */ 18. What is the difference between far and near? Some compilers for PC compatibles use two types of pointers. near pointers are 1 6 bits long and can address a 64KB range. far pointers are 32 bits long and can address a 1MB range. Near pointers operate within a 64KB segment. Theres one segment for function addr esses and one segment for data. far pointers have a 16-bit base (the segment add ress) and a 16-bit offset. The base is multiplied by 16, so a far pointer is eff ectively 20 bits long. Before you compile your code, you must tell the compiler which memory model to use. If you use a smallcode memory model, near pointers ar e used by default for function addresses. That means that all the functions need to fit in one 64KB segment. With a largecode model, the default is to use far function addresses. Youll get near pointers with a small data model, and far pointers with a large data model. These are ju st the defaults; you can declare variables and functions as explicitly near or f ar. far pointers are a little slower. Whenever one is used, the code or data segment register needs to be swapped out. far pointers also have odd semantics for arit hmetic and comparison. For example, the two far pointers in the preceding exampl e point to the same address, but they would compare as different! If your progra

m fits in a small-data, small-code memory model, your life will be easier. 19. When should a far pointer be used? Sometimes you can get away with using a small memory model in most of a given pr ogram. There might be just a few things that dont fit in your small data and code segments. When that happens, you can use explicit far pointers and function dec larations to get at the rest of memory. A far function can be outside the 64KB s egment most functions are shoehorned into for a small-code model. (Often, librar ies are declared explicitly far, so theyll work no matter what code model the pro gram uses.) A far pointer can refer to information outside the 64KB data segment . Typically, such pointers are used with farmalloc() and such, to manage a heap separate from where all the rest of the data lives. If you use a small-data, lar ge-code model, you should explicitly make your function pointers far. 20.Can math operations be performed on a void pointer? No. Pointer addition and subtraction are based on advancing the pointer by a num ber of elements. By definition, if you have a void pointer, you dont know what its pointing to, so you dont know the size of what its pointing to. If you want point er arithmetic to work on raw addresses, use character pointers. 21.Why should we assign NULL to the elements (pointer) after freeing them? This is paranoia based on long experience. After a pointer has been freed, you c an no longer use the pointed-to data. The pointer is said to dangle; it doesnt po int at anything useful. If you NULL out or zero out a pointer immediately after freeing it, your program can no longer get in trouble by using that pointer. Tru e, you might go indirect on the null pointer instead, but thats something your de bugger might be able to help you with immediately. Also, there still might be co pies of the pointer that refer to the memory that has been deallocated; thats the nature of C. Zeroing out pointers after freeing them wont solve all problems; 22. How can I access memory located at a certain address? Ans :by using pointer variable we can access memory located at certain address l ocation. 23.What is the memory allocated by the following definition ? int (*x)[10]; Ans: The pointer x will occupy 4bytes of memory. 24.What is the memory allocated by the following definition ? int (*x)(); Ans: The pointer x will occupy 4bytes of memory. 25.Whats the mistake in the following code? #include <stdio.h> int main() { int* ptr1,ptr2; ptr1 = malloc(sizeof(int)); ptr2 = ptr1; *ptr2 = 10; return 0; } 26. void main() { char far *farther,*farthest; printf("%d..%d",sizeof(farther),sizeof(farthest)); } Answer:

4..2 Explanation: the second pointer is of char type and not a far pointer 27.main() { char *p; p="Hello"; printf("%c\n",*&*p); } Answer: H Explanation: * is a dereference operator & is a reference operator. They can be applied a ny number of times provided it is meaningful. Here p points to the first chara cter in the string "Hello". *p dereferences it and so its value is H. Again & r eferences it to an address and * dereferences it to the value H. 28) main( ) { char *q; int j; for (j=0; j<3; j++) scanf(%s ,(q+j)); for (j=0; j<3; j++) printf(%c ,*(q+j)); for (j=0; j<3; j++) printf(%s ,(q+j)); } Explanation: Here we have only one pointer to type char and since we take input in the same p ointer thus we keep writing over in the same location, each time shifting the po inter value by 1. Suppose the inputs are MOUSE, TRACK and VIRTUAL. Then for the first input suppose the pointer starts at location 100 then the input one is st ored as M O U S E \0 When the second input is given the pointer is incremented as j value becomes 1, so the input is filled in memory starting from 101. M T R A C K \0 The third input starts filling from the location 102 M T V I R T U A L \0 This is the final value stored . The first printf prints the values at the position q, q+1 and q+2 = M T V The second printf prints three strings starting from locations q, q+1, q+2

i.e MTVIRTUAL, TVIRTUAL and VIRTUAL. 29) main( ) { void *vp; char ch = g, *cp = goofy; int j = 20; vp = &ch; printf(%c, *(char *)vp); vp = &j; printf(%d,*(int *)vp); vp = cp; printf(%s,(char *)vp + 3); } Answer: g20fy Explanation: Since a void pointer is used it can be type casted to any other type pointer. v p = &ch stores address of char ch and the next statement prints the value store d in vp after type casting it to the proper data type pointer. the output is g. Si milarly the output from second printf is 20. The third printf statement type cast s it to print the string from the 4th value hence the output is fy. 30.main() { int *j; { int i=10; j=&i; } printf("%d",*j); } Answer: 10 Explanation: The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the ex it of main function. Since the i is still allocated space, *j prints the value s tored in i since j points i. 31.# include<stdio.h> aaa() { printf("hi"); } bbb(){ printf("hello"); } ccc(){ printf("bye"); } main() { int (*ptr[3])(); ptr[0]=aaa; ptr[1]=bbb; ptr[2]=ccc; ptr[2](); } Answer: bye

Explanation: ptr is array of pointers to functions of return type int.ptr[0] is assigned to a ddress of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respecti vely. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc. 32.void main() { void *v; int integer=2; int *i=&integer; v=i; printf("%d",(int*)*v); } Answer: Compiler Error. We cannot apply indirection on type void*. Explanation: Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void pointers are normally used for, 1.Passing generic pointers to functions and returning such pointers. 2.As a intermediate pointer type. 3.Used when the exact pointer type will be known at a later point of time. 33)main() { int a=2,*f1,*f2; f1=f2=&a; *f2+=*f2+=a+=2.5; printf("\n%d %d %d",a,*f1,*f2); } Answer: 16 16 16 Explanation: f1 and f2 both refer to the same memory location a. So changes through f1 and f2 ultimately affects only the value of a. 34.main() { int i = 257; int *iPtr = &i; printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) ); } Answer: 1 1 Explanation: The integer value 257 is stored in the memory as, 00000001 00000001, so the indi vidual bytes are taken by casting it to char * and get printed. 35.main() { int i = 258; int *iPtr = &i; printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) ); } Answer: 2 1 Explanation: The integer value 257 can be represented in binary as, 00000001 00000001. Rememb er that the INTEL machines are small-endian machines. Small-endian means that the lower order bytes are stored in the higher memory addresses and the higher order bytes are stored in lower addresses. The integer value 258 is stored in memory as: 00000001 00000010. 36) { main()

int i=300; char *ptr = &i; *++ptr=2; printf("%d",i); } Answer: 556 Explanation: The integer value 300 in binary notation is: 00000001 00101100. It is stored i n memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory representation as: 00101100 00000010. So the integer corresp onding to it is 00000010 00101100 => 556. 37) #include <stdio.h> main() { char * str = "hello"; char * ptr = str; char least = 127; while (*ptr++) least = (*ptr<least ) ?*ptr :least; printf("%d",least); } Answer: 0 Explanation: After ptr reaches the end of the string the value pointed by str is \0. So the value o f str is less than that of least. So the value of least finally is 0. 38.void main() { int *i = 0x400; // i points to the address 400 *i = 0; // set the value of memory location pointed by i; } Answer: Undefined behavior Explanation: The second statement results in undefined behavior because it points to some loc ation whose value may not be available for modification. This type of pointer i n which the non-availability of the implementation of the referenced location is known as incomplete type. 39.The following C program segfaults of IA-64, but works fine on IA-32. int main() { int* p; p = (int*)malloc(sizeof(int)); *p = 10; return 0; } Why does it happen so? 40.Can you add pointers together? Why would you? No, you cant add pointers together. If you live at 1332 Lakeview Drive, and you r neighbor lives at 1364 Lakeview, whats 1332+1364? Its a number, but it doesn t mean anything. If you try to perform this type of calculation with pointers i n a C program, your compiler will complain. The only time the addition of pointers might come up is if you try to add a poin ter and the difference of two pointers. 41.Are pointers integers?

No, pointers are not integers. A pointer is an address. It is merely a positive number and not an integer. 42.Whats the difference between the following two C statements? const char *p; char* const p; 43.#include <stdio.h> main() { int a,b=2,c; int *pointer; c = 3; pointer = &c; a = c/*pointer*/; b = c /* assigning 3 to b*/; printf("a = %d; b = %d", a,b); } Ans:a=3,b=3 44) #include<stdio.h> main() { int *i=0; printf(" %p\n",i); } Ans:%p is a format specifier which is used to print the address of a variable.th e output of the following program is nil.since the pointer variable is assigned with a null value. 45.#include<stdio.h> #include<stdlib.h> main() { int *ptr=(int*)malloc(sizeof(int)); *ptr=4; printf("%d",(*ptr)+++*ptr++); } Ans: 9 46) #include <stdio.h> main() { int a[] = {0,1,2,3,4}; int *p[] = {a,a+1,a+2,a+3,a+4}; int **pp = p; printf("%d, %d, %d ", *pp-a, pp-p, **pp); pp++; pp++;;++pp;*++pp; printf("%d, %d, %d ", pp-p, *pp-a, **pp); } ans:0,0,0 4 ,4,4 47.#include <stdio.h> main() { const int i = 100; int *p = &i; *p = 200; printf("%d\n",i);

} ans:200.

Dynamic memory allocation: 1.Difference between malloc( ) and calloc( ) ? Ans:Dynamic memory allocation is nothing but allocating memory at runtime . Whatever the memory allocated dynamically will have the storage in HEAP sectio n of processes image. MALLOC() CALLOC( ) Allocates specified no. of bytes of memory. Allocates space for specified no. of objects of specified size. Requires one argument. 1.Size in bytes. Requires two arguments. 1. No. of objects of same type. 2. Size of the object. Allocated memory is not initialized, that means memory will have garbage values. Allocated memory is initialized with zeros. Syntax: Void *malloc(size_t size); Syntax Void *calloc(size_t numOfElms,size_t sizeOfObject); 2.How do you dynamically allocate 1-D and 2-D array of integers? Ans:1-D #define MAX 10 Int main( ) { Int *p, i; P=(int *)malloc(MAX*sizeof(int)); For(i=0;i<MAX;i++) { P[i]= i; Printf(%d,p[i]); } Return 0; } 2-D: #define MAXROW 3 #define MAXCOL 4 Int main( ) { Int *p,I,j; P=(int *)malloc(MAXROW*MAXCOL*sizeof(int)); For(i=0;i<MAXROW;i++) { For(j=0j<MAXCOL;j++) { P[i*MAXCOL+j]=i; Printf(%d,p[i*MAXCOL+J]); } Printf(\n); } Return 0;

} 3.How can you increase the size of a dynamically allocated array? Ans:We can increase the size of a dynamically allocated array by using rell oc( ) function. Ex:- int main( ) { Char *p; P=(char *)malloc(20); Strcpy(p,Go embedded); Printf(string=%s\naddress=%d\n,p,p); P=(char *)realloc(p,60); Strcpy(p,Go embedded because thats well feature ); Printf(after string=%s\n address=%d\n,p,p); Return 0; } 4.When reallocating memory if any other pointer point into the same piece of mem ory do you have to readjust these other pointers (or) do they get readjusted automatically? Ans:If realloc() expands allocated memory at the same place then there i s no need of readjustment of other pointers. However , if it allocates a new reg ion somewhere else the programmer has readjust the other pointer. 5.Which function should be used to free the dynamically allocated Ans:free(p); memory?

6.How much max can you allocate in a single call to malloc( )? Ans:The largest possible block that can be allocates using malloc( ) depend s upon the host system-particularly the size of physical memory and the os imple mentation. 7.Can you dynamically allocate arrays in extended memory? Ans:- Using standard library functions for malloc( ) we can dynamically allocat e array is extended memory. 8. why does malloc(0) return valid memory address?. Whats the use? Ans:- malloc( ) returns a NULL if it fails to allocate requested memory. 9.what happens if we try to use malloc( ) or calloc( ) outside the function? Ans:10.what is the ouput of the following program. int main() { } char *a= "Novell"; char *b; b=malloc(10*sizeof(char)); memset(b,0,10); while(*b++=*a++); printf("%s",b); return 0; Ans: no output 11.Why does malloc(0) return valid memory address ? Whats the use ?

malloc(0) does not return a non-NULL under every implementation. An implementati on is free to behave in a manner it finds suitable, if the allocation size reque sted is zero. The implementation may choose any of the following actions: * A null pointer is returned. * The behavior is same as if a space of non-zero size was requested. In this cas e, the usage of return value yields to undefined-behavior. Notice, however, that if the implementation returns a non-NULL value for a reque st of a zero-length space, a pointer to object of ZERO length is returned! Think , how an object of zero size should be represented? For implementations that return non-NULL values, a typical usage is as follows: void func ( void ) { int *p; /* p is a one-dimensional array, whose size will vary during the the lifetime of the program */ size_t c; p = malloc(0); /* initial allocation */ if (!p) { perror (FAILURE ); return; } /* */ while (1) { c = (size_t) ; /* Calculate allocation size */ p = realloc ( p, c * sizeof *p ); /* use p, or break from the loop */ /* */ } return; } Notice that this program is not portable, since an implementation is free to ret urn NULL for a malloc(0) request, as the C Standard does not support zero-sized objects. 12.#include <stdio.h> #include<stdlib.h> #include<ctype.h> main() { int *p, *c, i; i = 5; p = malloc(sizeof(i)); printf("\n%d",*p); *p = 10; printf("\n%d %d",i,*p); c = calloc(2,i); printf("\n%d\n",*c);

} Ans:0 5,10,0 13.What is the difference between memcpy and memmove? 14.#include <stdio.h> #include<malloc.h> main() { int *iptr,*dptr, i; dptr = malloc(sizeof(i)); iptr =&i ; *iptr = 10; free(iptr); *dptr = 20; /*dptr = iptr;*/ free(dptr); printf("%d,%d,%d",*dptr,*iptr,i); } 15. #include<stdio.h> #include<stdlib.h> main() { int *ptr=(int*)malloc(sizeof(int)); *ptr=4; printf("%d",*ptr++); } ans:4 Arrays 1.Difference between Structure and Arrays? Ans:STRUCTURE ARRAY *Structure is a collection of elements of dissimilar data types. *Structure is represent the compound type. *Array is a collection of similar data type elements. *Arrays are considered as vector type. 2.Difference between Strings and Arrays? Ans:STRINGS ARRAY *String is nothing but set of characters ended with NULL character. Strings requ ire one byte more than string length to accommodate \o character. *Array can be any type of data where as strings are only of char type. 3.Equivalent pointer to a[i][j][k][l]? Ans:A[i][j][k][l]=*(*(*(*(A+i)+j)+k)l); 4.Are the expressions arr and &arr same for an array ? Ans:- No, even though both may give the same address, they mean two different things. Array gives the address of the first int, where as &arr gives the address of arr ay of ints. Since these addresses happen to be same the result of the expression

are same. The expression arr+1 will give the address of the next integer , where as &a rr+1 will give the address of next array of integers. 5.Does mentioning the array name gives the base address in all the contexts? Ans:- No, where mentioning the array name gives its base address it is said tha t array has decayed(decomposed) in to a pointer . this decaying doesnt take place two situations: * When array name is used with the sizeof operator. * When the array name is an operand of the &operator. 6.Explain one method to process an entire array as one unit? Ans:7.How do you dynamically allocate 1-D and 2-D array of integers? Ans:Refer: DMA 2nd question. 8.How can you increase the size of a dynamically allocated array? Ans:- Refer: DMA 3rd question. 9. Can you increase the size of a statically allocated array? Ans:No. 10.What are the characteristics of arrays in C? 1) An array holds elements that have the same data type 2) Array elements are stored in subsequent memory locations 3) Two-dimensional array elements are stored row by row in subsequent memory loc ations. 4) Array name represents the address of the starting element 5) Array size should be mentioned in the declaration. Array size must be a const ant expression and not a variable. 11.The expected output of the following C program is to print the elements in th e array. But when actually run, it doesnt do so. #include<stdio.h> #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] = {23,34,12,17,204,99,16}; int main() { int d; for(d=-1;d <= (TOTAL_ELEMENTS-2);d++) printf("%d\n",array[d+1]); return 0; } Ans:here the loop is not executed as it doesnt know the value of TOTAL_ELEMENTS. 12. what is the o/p main() { char a[3][4]={ "abcd", "efgh", "ijkl" }; putchar(**a); } a) syntax error b) prints some letter in those given c) prints garbage value

d) The above program may not be the exact one but the same with small changes in the letters given above. Ans:a 13) { main()

char p[ ]="%d\n"; p[1] = c; printf(p,65); } Answer: A Explanation: Due to the assignment p[1] = c the string becomes, %c\n. Since this string becomes t he format string for printf and ASCII value of 65 is A, the same gets printed. 14.#include<stdio.h> main() { int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} }; int *p,*q; p=&a[2][2][2]; *q=***a; printf("%d..%d",*p,*q); } Answer: garbagevalue..1 Explanation: p=&a[2][2][2] you declare only two 2D arrays. but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a start ing address of a is assigned integer pointer. now q is pointing to starting addr ess of a.if you print *q meAnswer:it will print first element of 3D array. 15.Can the sizeof operator be used to tell the size of an array passed to a func tion? No. Theres no way to tell, at runtime, how many elements are in an array paramete r just by looking at the array parameter itself. Remember, passing an array to a function is exactly the same as passing a pointer to the first element. 16.main() { char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]); } Answer: mmmm aaaa nnnn Explanation: s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. G enerally array name is the base address for that array. Here s is the base addr ess. i is the index number/displacement from the base address. So, indirecting i t with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i]. 17.#include<stdio.h> main() {

char s[]={a,b,c,\n,c,\0}; char *p,*str,*str1; p=&s[3]; str=p; str1=s; printf("%d",++*p + ++*str1-32); } Answer: 77 Explanation: p is pointing to character \n. str1 is pointing to character a ++*p. "p is p ointing to \n and that is incremented by one." the ASCII value of \n is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is point ing to a that is incremented by 1 and it becomes b. ASCII value of b is 98 . Now performing (11 + 98 32), we get 77("M"); So we get the output 77 :: "M" (Ascii is 77). 18.#include main() { int int for <stdio.h> arr[3][3] = {1,2,3,4,5,6,7,8,9}; i,j; (j=2;j>=0;j--){ for(i=2;i>=0;i--){ printf("\n%d",*(*(arr+i)+j)); printf("\n TATATATA"); }

} } 19.#include <stdio.h> main() { int a[3] = {1,2,3}; int i= 2; printf("\n %d %d\n", a[i], i[a]); } Ans:3 3

20.#include<stdio.h> main() { int a[]={2,3,4,5,6}; int i=0; printf("%d",a[i++]+i[a+1]); } Ans:5.here post increment operation is performed on i.It will be incremented aft er the operation is performed. 21..#include<stdio.h> main() { int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} }; int *p,*q; p=&a[2][2][2]; *q=***a;

printf("%d----%d",*p,*q); } Answer: SomeGarbageValue---1 Explanation: p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a start ing address of a is assigned integer pointer. Now q is pointing to starting addr ess of a. If you print *q, it will print first element of 3D array. 22.When does the compiler not implicitly generate the address of the first eleme nt of an array? Whenever an array name appears in an expression such as - array as an operand of the sizeof operator - array as an operand of & operator - array as a string literal initializer for a character array Then the compiler does not implicitly generate the address of the address of the first element of an array. main() { int a[10]; printf("%d",*a+1-*a+3); } Answer: 8 Explanation: *a and -*a cancels out. The result is as simple as 1 + 3 = 8! 23. How can I allocate arrays or structures bigger than 64K? main( ) { int a[2][3][2]= {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}}; printf(%u %u %u %d \n,a,*a,**a,***a); printf(%u %u %u %d \n,a+1,*a+1,**a+1,***a+1); } Answer: 100, 100, 100, 2 114, 104, 102, 3 Explanation: The given array is a 3-D one. It can also be viewed as a 1-D arr ay.

2 4 7 8 3 4 2 2 2 3 3 4 100 102 104 106 108 110 112 114 116 118 120 122 thus, for the first printf statement a, *a, **a give address of first element

. since the indirection ***a gives the value. Hence, the first line of the outpu t. for the second printf a+1 increases in the third dimension thus points to value at 114, *a+1 increments in second dimension thus points to 104, **a +1 increment s the first dimension thus points to 102 and ***a+1 first gets the value at firs t location and then increments it by 1. Hence, the output. 24.main( ) { int a[ ] = {10,20,30,40,50},j,*p; for(j=0; j<5; j++) { printf(%d ,*a); a++; } p = a; for(j=0; j<5; j++) { printf(%d ,*p); p++; } } Answer: Compiler error: lvalue required. Explanation: Error is in line with statement a++. The operand must be an lvalue and may be of any of scalar type for the any operator, array name only when subscripted is an lvalue. Simply array name is a non-modifiable lvalue. 25.main( ) { static int a[ ] = {0,1,2,3,4}; int *p[ ] = {a,a+1,a+2,a+3,a+4}; int **ptr = p; ptr++; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); *ptr++; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); *++ptr; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); ++*ptr; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); } Answer: 111 222 333 344 Explanation: Let us consider the array and the two pointers with some address a 0 1 2 3 4 100 102 104 106 108 p 100 102

104 106 108 1000 ptr 1000 2000 After execution of the instruction ptr++ value in ptr becomes 1002, if scaling f actor for integer is 2 bytes. Now ptr p is value in ptr starting location of arr ay p, (1002 1000) / (scaling factor) = 1, *ptr a = value at address pointed by ptr starting value of array a, 1002 has a value 102 so the value is (102 100)/( scaling factor) = 1, **ptr is the value stored in the location pointed by the pointer of ptr = value pointed by value pointed by 1002 = value pointed by 102 = 1. Hence the output of the firs printf is 1, 1, 1. After execution of *ptr++ increments value of the value in ptr by scaling factor , so it becomes1004. Hence, the outputs for the second printf are ptr p = 2, *pt r a = 2, **ptr = 2. After execution of *++ptr increments value of the value in ptr by scaling factor , so it becomes1004. Hence, the outputs for the third printf are ptr p = 3, *ptr a = 3, **ptr = 3. After execution of ++*ptr value in ptr remains the same, the value pointed by th e value is incremented by the scaling factor. So the value in array p at locatio n 1006 changes from 106 10 108,. Hence, the outputs for the fourth printf are pt r p = 1006 1000 = 3, *ptr a = 108 100 = 4, **ptr = 4 26) main ( ) { static char *s[ ] = {black, white, yellow, violet}; char **ptr[ ] = {s+3, s+2, s+1, s}, ***p; p = ptr; **++p; printf(%s,*--*++p + 3); } Answer: ck Explanation: In this problem we have an array of char pointers pointing to start of 4 strings . Then we have ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer to a pointer of type char. p hold the initial v alue of ptr, i.e. p = s+3. The next statement increment value in p by 1 , thus n ow value of p = s+2. In the printf statement the expression is evaluated *++p c auses gets value s+1 then the pre decrement is executed and we get s+1 1 = s . t he indirection operator now gets the value from the array of s and adds 3 to the starting address. The string is printed starting from this position. Thus, the output is ck. 27.main() { char *str1="abcd"; char str2[]="abcd"; printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd")); } Answer: 2 5 5 Explanation: In first sizeof, str1 is a character pointer so it gives you the size of the poi nter variable. In second sizeof the name str2 indicates the name of the array wh ose size is 5 (including the \0 termination character). The third sizeof is si milar to the second one. 28.What is the output for the following program 1002 1004 1006 1008

main() { int arr2D[3][3]; printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) ); } Answer 1 Explanation This is due to the close relation between the arrays and pointers. N dimensional arrays are made up of (N-1) dimensional arrays. arr2D is made up of a 3 single arrays that contains 3 integers each .

The name arr2D refers to the beginning of all the 3 arrays. *arr2D refers to the start of the first 1D array (of 3 integers) that is the same address as arr2D. So the expression (arr2D == *arr2D) is true (1). Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesnt change the va lue/meaning. Again arr2D[0] is the another way of telling *(arr2D + 0). So the e xpression (*(arr2D + 0) == arr2D[0]) is true (1). Since both parts of the expression evaluates to true the result is true(1) and t he same is printed. 29.main() { static int a[3][3]={1,2,3,4,5,6,7,8,9}; int i,j; static *p[]={a,a+1,a+2}; for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("%d\t%d\t%d\t%d\n",*(*(p+i)+j), *(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i)); } } Answer: 1 1 1 1 2 4 2 4 3 7 3 7 4 2 4 2 5 5 5 5 6 8 6 8 7 3 7 3 8 6 8 6 9 9 9 9 Explanation: *(*(p+i)+j) is equivalent to p[i][j]. 30.#include <stdio.h> main() { int a[3][4] ={1,2,3,4,5,6,7,8,9,10,11,12} ; int i,j,k=99 ; for(i=0;i<3;i++) for(j=0;j<4;j++)

if(a[i][j] < k) k = a[i][j]; printf("%d", k); } Ans:1

Strings 1.strdup( ) ? Ans:- The strdup( ) function returns a pointer to a new string , which is a dupl icate of the string with different address . Syntax:- char *b=strdup(a); 2.strcpy( )? Ans:- It copies a string .strcpy( ) function is used to copy the contents of s tring2 in to string1. String2 must be a pointer to a null-terminated string. The strcpy( ) function returns a pointer to strins1. **Program using strcpy( ) function: Int main( ) { Char source[]=aketimicrosys; Char target[20]; Strcpy(target,source); Printf(source=%s\n target=%s\n,source,target); } **Program without using strcpy( ) function: Int main( ) { Char source[]=aketimicrosys; Char target[20]; My_strcpy(target,source); Printf(source=%s\n target=%s\n,source,target); } My_strcpy(char *t, char *s ) { While(*s) { *t=*s; s++; t++; } *t=\0; } 3.Difference between Strings and Arrays? Ans:4.Compare two strings without strcmp()? Ans:- strcmp( ) is a function which compare two strings to find out whether the y are same or different. The two strings are compared character by character un til there is mismatch or end of one strings are identical, strcmp( ) returns a v alue zero. If they are not, it returns the numeric difference b/w the ascii valu e of the non-matching characters. **Program, compare two strings without strcmp( ): Int main() { Char string1[]=aketimicrosys; Char string2[]=aketimicrosys; Int i;

i=my_strcmp( string1,string2); if(i==0) printf(Giving two strings are equal\n); else printf(Giving two strings are not equal\n); } Int my_strcmp(char *s1,char *s2) { While((s1!=\0)&&(s2!=\0)) { If(s1!=s2) { Return 1; } Else { S1++; S2++; } } If((s1==\0)&&(s2==\0)) { Return 0; } Else { Return 1; } } 5.Concatenate two strings? Ans:- strcat( ) function concatenate the source string at the end of the target string. Ex:Int main( ) { Char source[]=microsys; Char target[20]=aketi; My_strcat(target,source); Printf(source=%s\n target=%s\n,source,target); } Void My_strcat(char *t, char *s) { While(*t!=\0) { t++; } t++= ; while(*s!=\0) { t++; *t=*s; s++; } } 6.String reverse? Ans:- It is reversing the given string 7.String length? Ans:- strlen( )counts the number of characters present in a string.

Int main( ) { Char arr[]=aketimicrosys; Int len; Len=my_strlen(arr); Printf(string=%s\n length=%d\n, arr, len); } Int my_strlen(char *s) { Int length=0; While(*s!=\0) { Length++; S++; } Return(length); } 8. what is string constant? Ans:- * string constant is nothing but set of character enclosed with in double quotes. *String constants will be stored in code section of process image. Code section is read only memory and if user tries to change the contents( doing ill egal operation) of read only memory at runtime , we will end up with segmentatio n faults/crash. So string constants are not modifiable at runtime. * String constants occupy memory, so we can maintain pointer to the string c onstants. String pointer reference stored in stack section. 9.difference between "abc" and A? Ans:- abc is string constant where as A is character constant. 10.Difference between strlen("Aketi") and sizeof("aketi"); Ans:strlen(aketi);---------- output:5 bytes. Sizeof(aketi);--------- output:6 bytes(including\0). 11.Difference between A and "a"? Ans:-A---- It is character constant and size is: 1 byte. a---- It is string constant and size is : 2 bytes(including \0 character). 12.Difference between sizeof(A) and sizeof("a")? Ans:- sizeof(A);---- output: 1 byte. Sizeof(a);--- output: 2 bytes(including \0 character ). 15.What is the output of the following, if the input provided is: Life is beautiful #include <stdio.h> int main() { char dummy[80]; printf("Enter a string:\n"); scanf("%[^a]",dummy); printf("%s\n",dummy); return 0; } 16.#include <stdio.h> main() { char line[80]; gets(line); puts(line);

} 17.#include <stdio.h> main() { int ptr[] = {1,2,23,6,5,6}; char str[] = {a,b,c,d,e,f,g,h}; printf("pointer differences are %ld, %d",&ptr[3], &str[3]-&str[0]); } Ans: address of ptr[3] is printed and 3 is printed. 18.#include <stdio.h> main() { char *arr = "This is to test"; printf("\n%c %c ",*(arr), *(arr++)); } Ans:h,t 19) #include<stdio.h> #include<string.h> main() { char a[]="aaa"; char *b="bbb"; strcpy(a,"cc"); printf("%s",a); strcpy(b,"dd"); printf("%s",b); } Ans:cc 20.#include <stdio.h> main() { char *p = "hello world!"; *(p+0) = H; printf("%s",p); } Ans:it results in segmentation fault .as we cannot change the code in the text s ection .it is read only. 21.#include <stdio.h> main() { char *p="abc"; char *q="abc123"; while(*p==*q) { printf("%c %c",*p,*q); p++;q++; } } Ans:a a b b c c 22.#include <stdio.h> #include<malloc.h> #include<string.h> main() { char *s2, *s1 ;

// //

s1 = malloc(sizeof(char) * 1000); s1 = "Hello, "; s2 = malloc(sizeof(char) * 10); s2 = "world!"; strcat(s1, s2); printf("%s", s2);

} 23) #include <stdio.h> char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}"; main() { printf(s,34,s,34); } 24) #include <stdio.h> #include<string.h> main() { char *s1 = "alpha", *s2 = "alpha"; if(!strcmp(s1,s2)) printf("yes\n"); } 25.#include <stdio.h> main() { char a= A; if( (a==Z)||( (a=L)&&( a==A))) a=a; printf("%c",a); printf(" Nothing "); } 26.#include <stdio.h> int myfunc(char *str) { char *ptr =str; while(*ptr++); return ptr-str-1; } main() { printf("%d", myfunc("DESIS")); } 27) #include <stdio.h> main() { char input[] = "SSSWILTECH1\1\1"; int i, c; for ( i=2; (c=input[i])!=\0; i++) { switch(c) { case a: putchar (i); continue; case 1: break;

case 1: while (( c = input[++i]) != \1 && c!= \0); case 9: putchar(S); case E: case L: continue; default: putchar(c);continue; } putchar(\n); } putchar( );

} Ans: switch s 28) #include <stdio.h> main() { unsigned int k = 987 , i = 0; char trans[10]; do {

trans[i++] = (k%16 > 9) ? (k%16 - 10 + a) : (k%16 - 0 );

} while(k /= 16); for(i=0;i<10;i++) printf("%c", trans[i]); } 29) #include <stdio.h> main() { unsigned int k = 987 , i = 0; char trans[10]; do { trans[i++] = (k%16 > 9 ? k%16 - 10 + a : k%16 - 0 ); printf("%d %d\n",k,k%16);

} while(k /= 16); printf("%s\n", trans); } 30) #include <stdio.h> main() { char *pk; const char* p; const char c = a; char c1=b; p=&c1; pk = &c; printf("%c %c",*pk,*p); }

31) #include<stdio.h>

#include<string.h> int s(char*A[20],char*B[20]) { char *a,*b; a=A,b=B; while(*a++!=*b++); *a=*b=\0; return strlen(A); } int main() { char A[20]="somestring",B[20]="debugthecbug"; printf("%d %s %s\n",s(&A,&B),A,B); return 0; } 32) #include<stdio.h> void insert(char a[],int n) { int i,j; for(i=j=0;a[i]!=\0;i++) if(a[i]!=n) a[j++]=a[i]; a[j]=\0; } main() { char a[]="helloworld"; insert(a,l); printf("%s",a); } 33) #include <stdio.h> int i; main() { char a[] = "Shiva"; printf("%c\n",i[a]); } ans:s 34.#include <stdio.h> void print_in_reverse( char *str ) { if( *str == \0 ) return; print_in_reverse(str+1); printf( "%c" , *str ); } main() { print_in_reverse( "char *str" ); }

Ans: rts* rahc 35.#include <stdio.h> main() { char str[] = "Taj is 2 miles away"; int i; for(i=0;i<19;++i) if(isalpha(str[i]))printf("%c",toupper(str[i])); } Ans: TAJ IS MILES AWAY 36.#include <stdio.h> main() { int c; while((c=getchar()) != 0){ printf("%c",c); } } 37.What is the difference between Char a[ ]=string and char *a=String Ans: char a[ ]=string - in this the string constant is stored both in stack se ction and text section. Char *a=string .the pointer variable which is stored in the stacksection will stores the address of stringconstant which is stored in the textsection. 38.#include <stdio.h> #include<string.h> main() { char strp[] = "Never ever say no"; char *chp, c=e; int i,j; chp = strrchr(strp, c); i = chp-strp; for(j=0;j<=i;j++)printf("%c",strp[j]); } Ans:strrchr function returns the address of last occurrence of given character v ariable in the given string constant. 39.#include <stdio.h> main() { char str[] ="abcdef"; printf("str is %s",str); str = "DESIS"; printf("str is %s",str); } Ans:DESIS cannot be assigned to string str. 40.#include <stdio.h> #include<string.h> main() { char *str ="India pvt. ltd."; char *str1 = "DESIS"; printf("str is %s",str); printf("str is %s",str1);

strcpy(str,str1); printf("str is %s",str); } 41.#include <stdio.h> #include<string.h> main() { char str[] ="DESIS India pvt. ltd."; const char *str1= str; strcpy(str1,"DESHAW"); printf("str is %s",str); } 42.#include <stdio.h> main() { char c1,c2,c3; c1 = getc(stdin); putc(c1,stdout); // c2 = getche(); // putc(c2,stdout); c3 = getchar(); putc(c3,stdout); } ans:the getc function accepts a single character,and putc the character read int o stout .the next getchar reads the value of enter key which we had pressed dur ing the execution. 43.#include <stdio.h> main() { char a[5] = "abcd"; int b = 3; printf("%c\n",a[b]); printf("%c\n",((char *) b)[(int) a]); } Ans:d d 44.#include <stdio.h> main() { char s[] = "Bouquets and Brickbats"; printf("\n%c, ",*(&s[2])); printf("%s, ",s+5); printf("\n%s",s); printf("\n%c",*(s+2)); } Ans:u,ets and bricjbats,Bouquets and Brickbats,u 45) main() { int i, n; char *x = girl; n = strlen(x); *x = x[n]; for(i=0; i<n; ++i) {

printf(%s\n,x); x++; } } Answer: (blank space) irl rl l Explanation: Here a string (a pointer to char) is initialized with a value girl. The strlen fu nction returns the length of the string, thus n has a value 4. The next statemen t assigns value at the nth location (\0) to the first location. Now the string bec omes \0irl . Now the printf statement prints the string after each iteration it in crements it starting position. Loop starts from 0 to 4. The first time x[0] = \0 hence it prints nothing and pointer value is incremented. The second time it pri nts from x[1] i.e irl and the third time it prints rl and the last time it prints l an d the loop terminates.

Storage classes 1.Different storage classes in C? Ans:-There are 4 types of storage class. Storage class Specifier 1.Automatic storage class.------ auto. 2.Register storage class.-------- register. 3.Static storage class.----------- static. 4.Extern storage class.---------- extern. 2.What does static variable mean? Ans:- variable which are defined with static storage class specifier are called st atic variable. Static variables further divided into two categories,internal static variables a nd external static variables. Static variables are initialized only once.they are initilalized at compile time and stored in data section. 3.Where auto variables get stored? Ans:-all local variables including function parameters,by default they come unde r this class and are called as automatic variables. Storage Stack frame Default value Garbage value Scope Local to block in which the variable is defined Life time or visibility Till the control remains with in the block in which the variable is defined 4.Where global,static,local,register,free memory and C program instructions get stored? Ans:-Global data section. Static data section. Local stack section. Register cpu registers.

Free memory heap section Program instructions text.(code) 5.Describe about storage allocation,scope,life time of global,extern,static,loca l and register variables? Ans:Storage class specifier Storage allocation Scope Lifetime Global Data section To all files in program Until program is running Extern Data section Point of definition to end of file As long as program is running Static Data section Internal:local to block in which variable is defined External:point of definition to end of file As long as program is running Local Stack section Local to block in which the variable is defined. As long as function is executing. Register Cpu register Local to block in which the variable is defined Till control remains with in the block. 6.What are register variables ? Advantages and Disadvantages? Ans:-register variables are those variables which specified with register storage class specifier. we can specify register storage class to local variables which ar e accessed frequently to fasten the program execution. These variable are stored in cpu registers. they become and behave as local variables when cpu registers are not available to store. Cpu registers doesnt have any addresses, so we cannot maintain pointers to register variables so reference operator& is invalid for reg ister variables. 7.Uses of Typedef? Ans:- type def is used to create alias name for existing data types.these are wi dely used with structures , unions, function pointers and variables. 8.Difference between scope and life time? Ans:Scope : It determines to which parts of the program the variable or function i s available. Lifetime :It determines how long the variable lives when the program is running. 9. Different types of scopes? Ans:-1.block scope 2.prototype scope 3.function scope 4.file scope 5.program scope

10. what are internal static variables and external static variables? Ans:Internal static External static The variable defined inside a function with static storage storage class specifi er are called internal static variable The variable defined outside a function with static storage storage class specif ier are called external static variable The main property of internal static variable is value persistence between multi ple calls of the function in which this variable is defined Using static spcefier forcibly we can make availability of external variable str ictly from point of definition to end of file 11. What is BSS section? Ans:- Bss is the part of the memory where the operating system initializes the m emory block to zeroes.that is how the uninitiaalized global data and static data get default values as zero.this area is fixed and has static size. 12.How can we make the functions of one file not to available in other file? Ans:-We can make the functions static static function by defining the function w ith static specifier so that these functions will not be available to other files in the program. By default all functions defined in one file will be available to all files with in the same program, because of global scope of a function 13. Difference between extern and static storage specifiers? Ans:-*Variables defined outside of a function with extern storage class specifie r are called external static variable. The variable defined inside a function wi th static storage storage class specifier are called internal static variable *Using extern specifier a function can be able to access a variable defined else where. *Where as in static specifier, static variable is value persistence between mult iple calls of the same function in which variable is defined. *Scope of external storage class specifier is point of definition to end of file . *Scope of static storage specifier is local to block in which the variable is de fined. 14.what happens if we use pointers to registers variables? Ans:- Cpu registers doesnt have any addresses, so we cannot maintain pointers to register variables so reference operator& is invalid for register variables. 15.what is initialized and uninitialized data section? Ans:16.extern int i; Is it declaration statement or definition statement? Ans:-Declaration statement. 17. extern int i=10; will it give any error? What error? Ans:-Error will occur in linking phase. 18.If i(variable) is not defined in anywhere in the program and if we use exte rn int i in some file of the program. Will it compile? And will it give any error a nd what error if yes? Ans:-linking error. 19.why static variables are initialized only once?

Ans :-The property of static variable is value persistence between multiple call s of the same function in which this variable is defined so it is initialized on ly once. These variables are initialized at compile time. 20.what is the o/p of the program main() { incr(); incr(); incr(); } incr() { static int i; printf("%d",++i); } a) prints 123 b) prints 111 c) prints garbage value d) error Ans: a 21.#include<stdio.h> int fun1() { static int c=20; return --c; } int fun2() { static int c=1; return fun1()+c--; } int main() { int i=0; while(i<fun2()) printf("%d ",i++); return 0; } 22. #include <stdio.h> main() { extern int i; i=20; printf("%d\n",sizeof(i)); } Ans:the compiler will give an error as the compiler cannot link the extern varia ble. 23. #include <stdio.h> int *NEXT(register int i) { int *ipt; ipt = &i; ipt++; return ipt; }

main () { int j; printf("%d",(NEXT(j))); } Ans:registered variables doesnot hold any address. 24.#include <stdio.h> main() { auto int i = 0; printf("%d\n",i); { int i = 2; printf("%d\n",i); { i+=1; printf("%d\n",i); } printf("%d\n",i); } printf("%d\n",i); printf("%d\n",reset()); printf("%d\n",ret10()); printf("%d\n",reset()); printf("%d\n",ret10()); } int reset() { int j = 0; return(j); } int ret10() { static int i = 10; i+=1; return(i); } Ans:0 2 3 3 0 0 11 0 12 25. #include <stdio.h> static int a = 6; extern int a; main() { printf("%d",a); } Ans:6 26.#include <stdio.h> static int count; void f(int n)

{ int i; for(i =1;i<=n;i++) f(n-i); count++; } main() { extern int count; f(5); printf("%d",count); } 27.#include <stdio.h> f(int x,int *y) { x=*(y)+=2; } main() { static int a[5] = {2,4,6,8,10}; int i,b=5; for(i=0; i< 5;i++){ f(a[i],&b); printf("%d %d\n",a[i],b); } } Ans: 28.If we declare a variable with which of the following keyword so that its valu e will be automatically initialized to 0. a) auto b) static Ans:b 29.Can static variables be defined in a header file? A static variable can be defined in a header file, but this would cause each sou rce file that included the header file to have its own private copy of the varia ble, which is probably not what was intended. 30.void main() { int const * p=5; printf("%d",++(*p)); } Answer: Compiler error: Cannot modify a constant value. Explanation: p is a pointer to a "constant integer". But we tried to change the value of the "constant integer". 31.main() { extern int i; i=20; printf("%d",sizeof(i)); } Answer: Linker error: undefined symbol i. Explanation: extern declaration specifies that the variable i is defined somewhere else. The

compiler passes the external variable to be resolved by the linker. So compiler doesnt find an error. During linking the linker searches for the definition of i. Since it is not found the linker flags an error. 32.main() { printf("%d", out); } int out=100; Answer: Compiler error: undefined symbol out in function main. Explanation: The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error . 33. { void main()

static int i=i++, j=j++, k=k++; printf(i = %d j = %d k = %d, i, j, k); } Answer: i = 1 j = 1 k = 1 Explanation: Since static variables are initialized to zero by default. 34.main() { register int a=2; printf("Address of a = %d",&a); printf("Value of a = %d",a); } Answer: Compier Error: & on register variable Rule to Remember: & (address of ) operator cannot be applied on register variable s. 35.main() { extern i; printf("%d\n",i); { int i=20; printf("%d\n",i); } } Answer: Linker Error : Unresolved external symbol i Explanation: The identifier i is available in the inner block and so using extern has no use in resolving it. Note : This question has more to do with Linker than C language 36.We have three files a.c, b.c and main.c respectively as follows: a.c --int a; b.c --int a = 10; main.c ------

extern int a; int main() { printf("a = %d\n",a); return 0; } Lets see what happens, when the files are compiled together: bash$ gcc a.c b.c main.c bash$ ./a.out a = 10 Hmm!! no compilation/linker error!!! Why is it so?? 37.when should the volatile modifier be used? The volatile modifier is a directive to the compilers optimizer that operations involving this variable should not be optimized in certain ways. There are two special cases in which use of the volatile modifier is desirable. The first case involves memory-mapped hardware (a device such as a graphics adaptor that appea rs to the computers hardware as if it were part of the computers memory), and the second involves shared memory (memory used by two or more programs running s imultaneously). Most computers have a set of registers that can be accessed faster than the comp uters main memory. A good compiler will perform a kind of optimization called r edundant load and store removal. The compiler looks for places in the code where it can either remove an instruction to load data from memory because the value is already in a register, or remove an instruction to store data to memory becau se the value can stay in a register until it is changed again anyway. If a variable is a pointer to something other than normal memory, such as memory -mapped ports on a peripheral, redundant load and store optimizations might be d etrimental. For instance, heres a piece of code that might be used to time some operation: time_t time_addition(volatile const struct timer *t, int a) { int n; int x; time_t then; x = 0; then = t->value; for (n = 0; n < 1000; n++) { x = x + a; } return t->value - then; } In this code, the variable t-> value is actually a hardware counter that is bein g incremented as time passes. The function adds the value of a to x 1000 times, and it returns the amount the timer was incremented by while the 1000 additions were being performed. Without the volatile modifier, a clever optimizer might as sume that the value of t does not change during the execution of the function, b ecause there is no statement that explicitly changes it. In that case, theres n o need to read it from memory a second time and subtract it, because the answer will always be 0. The compiler might therefore optimize the function by making i t always return 0. If a variable points to data in shared memory, you also dont want the compiler to perform redundant load and store optimizations. Shared memory is normally use d to enable two programs to communicate with each other by having one program st ore data in the shared portion of memory and the other program read the same por tion of memory. If the compiler optimizes away a load or store of shared memory, communication between the two programs will be affected.

Functions 1.What is recursion?Advantages and Disadvantages? Ans:- Recursion is nothing calling itself and function call itself are called recursive function. Advantage: Can be used in place of where ever loops are used. Disadvantage: Recursive are slower than iterative, because iterative method do n ot have function call overhead. Recursive method should have more stack space than iterative method and the problem with recursion is stack overflow. 2.What is the scope of a function? Ans:- Availability of the objects only with in the function in which these objec ts were defined. Ex:- Local variables. By default functions are global scope. 3. Why should we use prototype for a function? A function prototype tells the compiler what kind of arguments a function i s looking to receive and what kind of return value a function is going to give back. This approach helps the compiler ensure that calls to a function are ma de correctly and that no erroneous type conversions are taking place. 4.What are the advantages of the functions? Debugging is easier It is easier to understand the logic involved in the program Testing is easier. Recursive call is possible Irrelevant details in the user point of view are hidden in functions Functions are helpful in generalizing the program Resuage of code across multiple programs 5. Why doesnt C have nested functions? 6. How can I call a function, given its name as a string? Ans: 7. How can I return multiple values from a function? Ans:by using function pointers we can return multiple values from a function. 8. #include <stdio.h> main() { int i=4; if (i>5) printf("Hi"); else f(i); } f(int j) { if (j>=4) f(j-1); else if(j==0)return; printf("Hi"); return; } Ans:HiHi 9. #include <stdio.h>

abc(int *i, int *j) { *i = *i + *j; *j = *i - *j; *i = *i - *j; } main() { int i = 5, j=10; abc(&i,&j); printf("%d..%d",i,j); } Ans:10,5.swaping of two variables using pointers. 10. #include <stdio.h> void fun(int, int*); main() { int j,i; int * intptr; printf("enter an integer\n"); scanf("%d",&i); intptr = &j; j = i; printf("i and j are %d %d \n",i,j); fun(j,intptr); printf("i is:%d",i); printf("\n j is:%d",j); } void fun(int k, int *iptr) { k++; (*iptr)++; return; } 11. #include <stdio.h> fun() { printf("Yes\n"); } #define fun() printf("No\n") main() { fun(); (fun)(); } Ans:NO, YES 12. What would be the output of the following program? main() { const int x=get(); printf("%d",x); } get()

{ return(20); } (a) 20 (b) garbage value (c) error (d) 0 ANS: a 13. #include <stdio.h> void test(int , int *); main() { int * iptr, j, k = 2; iptr = &j; j = k; printf( "%d %d ", k, j); test(j, iptr); printf("%d %d\n", k, j); } void test(int l, int *p) { l++; (*p)++; } 14. How many times the following program would print Jamboree? main() { printf("\n Jamboree"); main(); } (a) infinite number of times (b) 32767 times (c) 65535 times (d) till the stack does not overflow ANS:d 15.main() { main(); } Answer: Runtime error : Stack overflow. Explanation: main function calls itself again and again. Each time the function is called its return address is stored in the call stack. Since there is no condition to term inate the function call, the call stack overflows at runtime. So it terminates t he program and results in an error. 16) . void ( * abc( int, void ( *def) () ) ) (); Answer:: abc is a ptr to a function which takes 2 parameters .(a). an integer variable .(b). a ptrto a funtion which returns void. the return type of the functi on is void. Explanation: Apply the clock-wise rule to find the result. 17.#include<stdio.h> void OS_Solaris_print() { printf("Solaris - Sun Microsystems\n"); }

void OS_Windows_print() { printf("Windows - Microsoft\n"); } void OS_HP-UX_print() { printf("HP-UX - Hewlett Packard\n"); } int main() { int num; printf("Enter the number (1-3):\n"); scanf("%d",&num); switch(num) { case 1: OS_Solaris_print(); break; case 2: OS_Windows_print(); break; case 3: OS_HP-UX_print(); break; default: printf("Hmm! only 1-3 :-)\n"); break; } return 0; } Ans: functions decleration statements should not contain -value in its name.here e rror is due to the function name OS_HP-UX_print(). 18.Are the following two function prototypes same? int foobar(void); int foobar(); The following programs should be of some help in finding the answer: (Compile an d run both the programs and see what happens) Program 1: #include <stdio.h> void foobar1(void) { printf("In foobar1\n"); } void foobar2() { printf("In foobar2\n"); } int main() { char ch = a; foobar1(); foobar2(33, ch); return 0;

} ans:In Foobar1 ,In foobar2 Program 2: #include <stdio.h> void foobar1(void) { printf("In foobar1\n"); } void foobar2() { printf("In foobar2\n"); } int main() { char ch = a; foobar1(33, ch); foobar2(); return 0; } Ans:too many arguments are provided in foobar1 function. 19) #include<stdio.h> #include<stdlib.h> void weird(int*a) { a=(int*)malloc(sizeof(int)); } main() { int*a; weird(a); *a=6; printf("%d\n",*a); } 20.#include <stdio.h> #define INTPTR int * main() { INTPTR pi, pj; int i,j; i=10;j=20; pi = &j; pj = &j; j++; i= *pi; printf("%d,",i); j++; // i= *pj; printf("%d",pj); } Ans:10,21 21) #include <stdio.h> myread(a,b) {

printf("%d %d",a,b); } main() { myread(2,4); } Ans: 2,4 22.#include <stdio.h> int myfunc(char *str) { char *ptr =str; while(*ptr++); return ptr-str-1; } main() { printf("length is %d", myfunc("DESIS")); } Ans:function to find length of a given string 23) #include <stdio.h> funct(char* str) { printf("%s\n",str); } main() { static int ii = 1; int jj = 5; ii+=++jj; funct(ii+++ "Campus Interview"); } 24) #include <stdio.h> funct(str) { printf("%s\n",str); } main() { }

funct(---+"DEShaw");

25.#include <stdio.h> main() { int i = 3,j; j = add(++i); printf("i = %d *p= %d\n", i, j); } add(ii)

int ii; { ii++; printf("ii = %d\n", ii); } Ans: 5,4,7

26.#include <stdio.h> f( ) { printf("I am f()"); } extern f1(); main() { int i=10; f1(i); } f1(int i ) { printf("the i value is %d",i); f(); } 27.#include <stdio.h> unsigned char f(unsigned n) { static const unsigned char table[64] = { 0, 0, 0, 9, 0, 0, 10, 1, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0,15, 0, 0, 12, 0, 17, 3, 0, 0,0, 0, 0, 20, 6, 0, 0, 14,0, 0, 16, 19, 5, 13,0, 25, 30, 18, 4, 24, 29, 23, }; return table[((n & -n) * 0x1d0d73df) >> 26]; } main() { printf("%c",f(8)); }

11, 2, 21, 7, 22, 27,32, 8, 26,31, 0, 0, 28, 0

28.#include <stdio.h> main() { int i, n, m, b, x[25]; int f1(int, int, int j[25]); for(i=0;i<25;i++) x[i] = i; i=0; m = 24; b=f1(i, m, x); printf("res %d\n",b); } int f1( int p, int q, int a[25]) { int m1,m2;

if (q==0) return(a[p]); else { m1 = f1 (p, q/2, a); m2 = f1(p+q/2+1,q/2,a); if(m1<m2) return (m2); else return(m1); } } ans:res 24 30.I hope you know that ellipsis (...) is used to specify variable number of arg uments to a function. (What is the function prototype declaration for printf?) W hat is wrong with the following delcaration? int VarArguments(...) { /*....*/ return 0; } Structures and Unions 1. What is structure ? Ans:Structure is collection of elements of dissimilar data types. Element s of structure are called structure members. We can use following as structure m embers: *Any simple data type variables. * Arrays. * Structure variables/structure definitions. *Function pointers. 2. Difference between Structure and Arrays? Ans:- Refer arrays Q.No.1. 3. Difference between Structure and Unions? Ans:- * A union is essentially a structure in which all of the fields overlay ea ch other. * At a time only one field can be used. * We can write to one field and read from another. 4. What are enumerations? Ans:* Enumeration are unique types (user defined types) consists set of named intege r constants. * The type of enumeration constants are always int. A variable with enumeration ty pe stores one of the values of the enumeration set defined by that type. 5. Similarity between Structures ,Unions and Enumerations? Ans:-all of them let u define new data types for the exsisting data types. 6. Can a structure contain a pointer to itself? Ans:- if a structure has pointer to itself as a element then it is called a self referential structure.self referential structures are best way for implementing linked lists. As each node in the linked list point to the identical node ,so n ode structure should contain a pointer to the same structure. 7. How can u check whether the contents of two structures variables are same or

not? Ans:- there is no way that we can compare two structures directly.if we want to check whether the contents of two structure variables we have to explicitly comp are each member of the structure variable by using strcmp function. 8. How are structure parsing and returning implemented by the compiler? Ans:-when structures are parsed as arguments to functions ,the entire structure pushed onto the stack. For big structures this is an extra overhead. This overhe ad is avoided by parsing pointers to structures instead of actual structure. To return structure a hidden argument is generated by the compiler is passed to th e function. This argument points to a location where the returned structure is c opied. 9. How can we read/write structures from/to data files? Ans:-To write a structure we can use Fwrite(&e,sizeof(e),1,fp); Where e is a structure variable. A corresponding fread() is used to read the structure back from the file. 10. What are bit fields? What is the use of bitfields in an structure declaratio n? Ans:-bit fields allow you to specify some very small objects of a given number o f bits of length. Always bit fields must be used in association with structures and unions. Using bitfields we can pack several objects into a machine word(one element). The accessing mechanism of bitfields just same as accessing mechanism of structu res /union elements. 11. What is structure padding? Ans:- basically structures are used to store dissimilar data types. When structu re contain different type s of elements,the compiler tries to assign these eleme nts to natural boundaries. Aligning to their natural boundaries gives efficient data transfer between cpu and memory. Size of the structure has to be divisible by biggest element of the structure. Ex:struct { Char a; Short b; }; 4 bytes of memory is allotted. Reducing the padding: by arranging the elements types in either in increasing or decreasing order. We can completely eliminate the padding by using pragma pack Ex;#pragma pack(1) Using pragma pack ,the elements which are having more than the size 1 can be pla ced at address divisible by 1. We must use pragma pack option before the struct definition. The pragma pack opt ion which is defined at the structure definition will only be valid for that pra gma pack option. 12)What is the output of this program? #include ##include main() { typedef union { int a;

char b[10]; float c; } Struct; Struct x,y = {100}; x.a = 50; strcpy(x.b,"hello"); x.c = 21.50; printf("Union x : %d %s %f \n",x.a,x.b,x.c ); printf("Union y : %d %s %f \n",y.a,y.b,y.c); } 13.#include <stdio.h> #include<string.h> main() { struct emp1 { char *name; int age; }; struct emp2 { char *cp; struct emp1 e1; }e2 = {"ghi",{"jkl",123}}; struct emp1 e3 = {"rwer",2341}; printf("\n%s %d\n",e3.name,e3.age); printf("\n%s %s %d\n",e2.cp,e2.e1.name,e2.e1.age); } ans:rwer 2341 ghi jkl 123 14.#include <stdio.h> struct xyz { int xyz ; } ; main() { union xyz { int xyz; } ; } 15.#include <stdio.h> #include <stdio.h> struct s { char *st; struct s *sptr; }; main() { int i; struct s *p[3];

static struct s a[]={ {"abcd",a+1}, {"pqrs",a+2}, {"stuv",a} }; for( i=0;i<3;i++ ) p[i] = a[i].sptr; swap(*p,a); printf("%s %s %s \n",p[0]->st,(*p)->st, (*p)->sptr->st); } swap(p1,p2) struct s *p1,*p2; { char *temp; temp = p1->st; p1->st = p2->st; p2->st = temp; } ans:abcd abcd stuv 16.#include <stdio.h> main() { struct ist{ int x; int y; }; struct list{ int x; struct ist next; }head; head.x = 100; head.next.x=10; printf("%d %d", head.x,head.next.x); } Ans:100 10 17.#include <stdio.h> main() { typedef union { struct { char c1,c2; } s; long j; float x; } U; U example; example.s.c1 = a; example.s.c2 = b; example.j = 5; printf("%c %c %d", example.s.c1, example.s.c2, example.j); } Ans:5 18.#include <stdio.h> main()

{ struct s1 { char *str; struct s1 *ptr; }; static struct s1 arr[] = { {"Hyderabad",arr+1},{"Bangalore",arr+2}, {"Delhi",arr}}; struct s1 *p[3]; int i; for(i=0;i<=2;i++) p[i] = arr[i].ptr; printf("%s\n",(*p)->str); printf("%s\n",(++*p)->str); printf("%s\n",((*p)++)->str); }

19) #include <stdio.h> main() { struct test { char c; int i; char m; } t1; printf("%d %d\n",sizeof(t1), sizeof(t1.c)); } Ans:12,1 20.#include <stdio.h> main() { int i; struct { int left,y; }a; printf("%5d\n",a[i].left); } subscripted value is neither array nor pointer 21.#include <stdio.h> #include<malloc.h> struct test{ int f; }; struct test* f(struct test * (*fPtr)() ) { struct test *ptr = (struct test*) malloc(sizeof(struct test)); return ptr; } main() { f(f)->f;

} Ans:f(f)->f returns a 0 value . 22.#include <stdio.h> main() { struct emp { char name[20]; int age; float sal; }; struct emp e = {"Tiger"}; printf("\n%d %f",e.age,e.sal); } Ans:0,0.0000 23.#include <stdio.h> struct _tag { int i; union { int a; int b; }c; } a; main() { a.c.a=10; printf("test %d\n",a.c.b); } Ans:test 10 24.#include <stdio.h> main() { union { long l_e; float f_e; } u; long l_v; float f_v; l_v = u.l_e = printf("%f ", printf("%f ", f_v = u.f_e = printf("%d ", printf("%d ", } Floating Point Numbers: 1.What do you think would be the output of the following program and why? (If yo u are about to say "f is 1.0", I would say check it out again) #include <stdio.h> int main() { float f=0.0f;

10; (float)l_v); u.f_e); 3.555; (long)f_v); u.l_e);

int i; for(i=0;i<10;i++) f = f + 0.1f; if(f == 1.0f) printf("f is 1.0 \n"); else printf("f is NOT 1.0\n"); return 0; } Ans:f is not 1.0.we should not use comparision operation operators on floating point numbers. 123) 2.#include<stdio.h> main() { float x=3.14; printf("%e, %E, %f",x,x,x); } ans:the format specifiers %e %E gives the floationg point number in exponent for mat. 3. #include <stdio.h> int main() { float a = 12.5; printf("%d\n", a); printf("%d\n", *(int *)&a); return 0; } Whats the output of the following program and why? Ans:0,0 4.What is the output of the following program? #include <stdio.h> int main() { int i = 6; if( ((++i < 7) && ( i++/6)) || (++i <= 9)) ; printf("%d\n",i); return 0; } 5.What is the bug in the following program? #include <stdlib.h> #include <stdio.h> #define SIZE 15 int main() { int *a, i; a = malloc(SIZE*sizeof(int)); for (i=0; i<SIZE; i++) *(a + i) = i * i; for (i=0; i<SIZE; i++) printf("%d\n", *a++); free(a);

return 0; } write a program 1.Write a C function which does the addition of two integers without using the + operator. You can use only the bitwise operators.(Remember the good old metho d of implementing the full-adder circuit using the or, and, xor gates....) 2.Write a C program to find the smallest of three integers, without using any of the comparision operators. 3.Write a small C program to determine whether a machines type is little-endian or big-endian. 4.Write a C program which prints Hello World! without using a semicolon!!!

Bitwise operators 1. To which numbering system can the binary number 1101100100111100 be easily Converted to? Ans:-Hexa decimal ,since each 4 digit binary represents one hexadecimal digit. 2. Which bitwise operator is suitable for checking whether a particular bit is ON (or) OFF? Ans:- bitwise and (&) operator. 3.Which bitwise operator is suitable for turning OFF a particular bit in a numbe r? Ans:-bitwise and (&) operator is best suitable for turning off a particular bit. 4.Which bitwise operator is suitable for turning ON a particular bit in a number ? Ans:-bitwise or(|) operator. 5.Which one is equivalent to multiplying by 2? Ans:- one bitwise left shift is equivalent to multiplication by 2 6.How to find number of bit ones in a number using bit wise operators? Ans:-int main() { int a; int count =1; printf(enter value a:\n); scanf(%d,&a); while(a=a&(a-1)) { Count++; } Printf(%d\n,count); } 7.How to find whether the number is power of 2 or not using bit wise operators? Ans:-int main() { Int a=10; If(a&(a-1) { Printf(a is not a power of 2\n);

} Else { Printf(a is not a power of 2\n); } } 8.How do you find whether the given number is divisible by 8 or not by using bit wise operators? Ans:-if((a&(a-1))==0) { Printf(divisible by 8\n); } Else { Printf(not divisible by 8\n); } 9.Setting a particular bit? Ans:-if we want set nth bit of a then formula is a|(1<<n). 10.Resetting a particular bit? Ans:-if we want to reset nth bit of a then the formula is a&(~(1<<n) 11.Toggling a particular bit? Ans:-to toggle a particular bit of a formula is a^(1<<n) 12.setting the bits from mth bit tonth bit of number a? Ans:-a=a|((~(unsigned(0))>>((sizeof(unsigned)*8)-(m-n+1)))<<n) 13.Resetting the bits from mth bit to n th bit of number a? Ans:-a=a&(~(~(unsigned(0))>>(sizeof(unsigned)*8)-(m-n+1)))<<n)) 14.toggling the bits from mth bit to nth bit of number a? Ans:-a=a^((~(unsigned (0))>>((sizeof(unsigned)*8)-(m-n+1)))<<n) 15.What is the most efficient way to count the number of bits which are set in a value? Ans: the most efficient way to count the no of bits set in the given no is by us ing and Operation Ex:to find the no of bits set in a While(a) { Count++; a=a&(a-1) } Initialize the count value with 0 first. 16.Which bit wise operator is suitable for turning off a particular bit in a num ber? ans: bit wise and operator is best suitable for turning off the particular bit i n a number. 14.Here is a small piece of program(again just 14 lines of program) which counts the number of bits set in a number. Input Output 0 0(0000000)

5 2(0000101) 7 3(0000111) int CountBits (unsigned int x ) { static unsigned int mask[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF } ; int i ; int shift ; /* Number of positions to shift to right*/ for ( i =0, shift =1; i < 5; i ++, shift *= 2) x = (x & mask[i ])+ ( ( x >> shift) & mask[i]); return x; } Find out the logic used in the above program. 15.Here is yet another implementation of CountBits. Verify whether it is correct (how do you that???). If so, find out the logic used. int CountBits(unsigned int x) { int count=0; while(x) { count++; x = x&(x-1); } return count; } Ans:the logic used here is when we apply and operation between number and the ot her no which is one less than it the no of bits in the number will be reduced by one. 16.#include <stdio.h> main() { char c1; int i=0; c1=a; while(c1>=a && c1 <=z) { c1++; i++; } printf("%d",i); } Ans:26 17) #include <stdio.h> main() { int a=4,b=10; printf("%d %d %d %d\n",a,a^=b=b^=a=a^=b,b,printf("%d %d %d\n", b,a,a^=b=b^=a=a^=b)); }

Preprocessor 1. What are macros? Advantages and Disadvantages? Ans:-*Macros are also called text replacements. * whenever macro is used in the program that will be replaced with in the macro definition. *all macro names should must be written in upper case letters only score(_) between words in the macro name. *all macros will be started with #define Advantages:macros is used for writing small functions . Because if ons it will have function calling overhead whereas in macros there d.

text defined and use under we use functi is no overhea

2. Difference between Macro and Function? Ans:Function Macro Jumps to the function definition and executes where ever it is called Replaced with its macro definition where ever it is used Function calling overhead No overhead Execution time=jumptime+execution time+returntime Execution time=execution time of macro definition Program takes less space if functions are used and are called at multiple places Program takes more space if macros are used in multiple places. Compilation phase Preprocessor phase Parameter type checking No parameter type checking No side effects ,because in function,expressions are evaluated before passing th e values Side effects exists because.in macros expression are not evaluated before text r eplacement. Return values No return values Debugging is easy in function Debugging is hard using macros 3. Difference between Macro and Typedef? Ans:Macro Typedef These are expanede during preprocessing These are identified during c compilation Having global effect that means these are available to all parts of a program Typedef follow scope rules 4. Difference between NULL macro and NULL pointer? Ans:-Null macro is used to represent the null pointer in source code .It has a v alue 0 associated with it. Syntax:#define NULL (void *)0; A null pointer is a pointer which doesnt point any where. 5. What is the Scope of a macro? Ans:-scope of a macro is global effect i,e these are available to all parts of a program that means program scope.

6. What is the benefit of using an enum rather than a #define constant? Ans:-there is hardly any difference between the two ,except that a #define has a global effect,whereas,an enumeration can have an local effect to theblock it is defined. Advantages of enumerations are not that the numeric values are automatically ass igned ,whereas in #define we have to explicitly define them. Disadvantages of enumerations is that we have no control over the enumeration va riable. 1. What are the standard predefined macros? The ANSI C standard defines six predefined macros for use in the C langua ge: Macro Name _ _LINE_ _ _ _FILE_ _ _ _DATE_ _ _ _TIME_ _ _ _STDC_ _ _ _cplusplus _ _ Purpose Inserts the current source code line number in your code. Inserts the current source code filename in your code. Inserts the current date of compilation in your code. Inserts the current time of compilation in your code. Is set to 1 if you are enforcing strict ANSI C conformity. Is defined if you are compiling a C++ program.

2.The following is the offset macros which is used many a times. Figure out what is it trying to do and what is the advantage of using it. #define offsetof(a,b) ((int)(&(((a*)(0))->b))) 3.The following is the macro implementation of the famous, Triple xor swap. #define SWAP(a,b) ((a) ^= (b) ^= (a) ^= (b)) What are the potential problems with the above macro? 4.What is the use of the following macro? #define DPRINTF(x) printf("%s:%d\n",#x,x) 5.Lets say you were asked to code a function IAddOverFlow which takes three par ameters, pointer to an integer where the result is to be stored, and the two int egers which needs to be added. It returns 0 if there is an overflow and 1 otherw ise: int IAddOverFlow(int* result,int a,int b) { /* ... */ } So, how do you code the above function? (To put in a nutshell, what is the logic you use for overflow detection?) 6.What does the following macro do? #define ROUNDUP(x,n) ((x+n-1)&(~(n-1))) 7.Most of the C programming books, give the following example for the definition of macros. #define isupper(c) (((c) >= A) && ((c) <= Z)) But there would be a serious problem with the above definition of macro, if it i s used as follows (what is the problem??) char c; /* ... */ if(isupper(c++)) { /* ... */ }

But most of the libraries implement the isupper (declared in ctypes.h) as a macr o (without any side effects). Find out how isupper() is implemented on your syst em. 8.Write a C program to find the smallest of three integers, without using any of the comparision operators. 9) #include <stdio.h> #define PRINT(int) printf("int = %d ",int) main() { int x,y,z; x=03;y=02;z=01; PRINT(x^x); z<<=3;PRINT(x); y>>=3;PRINT(y); } 10.#include <stdio.h> #define DEBUG(args) (printf("DEBUG: "), printf args) main() { int n = 0,i = 0 ; printf("%d\n", n); if(n != 0) DEBUG(("n is %d\n", n)); DEBUG(("%d",i)); } 11) #include <stdio.h> #define PRINT(int) printf( "int = %d ", int) main() { int x=03,y=02,z=01; PRINT (x | y & ~z); PRINT (x & y && z); PRINT (x ^ y & ~z); } 12.#include <stdio.h> #define abs(x) x>0?x:-x #define mabs(x) (((x)>=0)?(x):-(x)) int kabs(int); main() { printf("\n%d %d",abs(10)+1,abs(-10)+1); printf("\n%d %d",mabs(10)+1,mabs(-10)+1); printf("\n%d %d\n",kabs(10)+1,kabs(-10)+1); } int kabs(int n) { return(n>0? n: -n); } 13. What is a pragma?

The #pragma preprocessor directive allows each compiler to implement compiler-sp ecific features that can be turned on and off with the #pragma statement. For in stance, your compiler might support a feature called loop optimization. This fea ture can be invoked as a command-line option or as a #pragma directive. To implement this option using the #pragma directive, you would put the followin g line into your code. #pragma loop_opt(on) Conversely, you can turn off loop optimization by inserting the following line i nto your code. #pragma loop_opt(off) 14. What is #line used for? The #line preprocessor directive is used to reset the values of the _ _LINE_ _ and _ _FILE_ _ symbols, respectively. 15.How do you override a defined macro? You can use the #undef preprocessor directive to undefine (override) a previousl y defined macro. 16. #define int char main() { int i=65; printf("sizeof(i)=%d",sizeof(i)); } Answer: sizeof(i)=1 Explanation: Since the #define replaces the string int by the macro char 17.#include <stdio.h> #define a 10 main() { #define a 50 printf("%d",a); } Answer: 50 Explanation: The preprocessor directives can be redefined anywhere in the program. So the mos t recently assigned value will be taken . 18.#define clrscr() 100 main() { clrscr(); printf("%d\n",clrscr()); } Answer: 100 Explanation: Preprocessor executes as a seperate pass before the execution of the compil er. So textual replacement of clrscr() to 100 occurs.The input program to compi ler looks like this : main() { 100;

printf("%d\n",100); } Note: 100; is an executable statement but with no action. So it doesnt give any probl em 19.#define f(g, g2) g##g2 main() { int var12=100; printf("%d",f(var,12)); } Answer: 100 20.#include <stdio.h> #define f(a,b) a##b #define g(a) #a #define h(a) g(a) int main() { printf("%s\n",h(f(1,2))); printf("%s\n",g(f(1,2))); return 0; } Just by looking at the program one "might" expect the output to be, the same for both the printf statements. But on running the program you get it as: bash$ ./a.out 12 f(1,2) bash$ Why is it so? 21.What is the output of the following program? (Again, it is not 40, (if the si ze of integer is 4)). #define SIZE 10 void size(int arr[SIZE]) { printf("size of array is:%d\n",sizeof(arr)); } int main() { int arr[SIZE]; size(arr); return 0; } Ans;the output of the above program gives array size as 4.which is a wrong answe r. 22.Whats the output of the following program. (No, its not 10!!!) #include <stdio.h> #define PrintInt(expr) printf("%s : %d\n",#expr,(expr)) int main() { int y = 100; int *p; p = malloc(sizeof(int)); *p = 10; y = y/*p; /*dividing y by *p */; PrintInt(y); return 0;

} 23.The following is a simple C program which tries to multiply an integer by 5 u sing the bitwise operations. But it doesnt do so. Explain the reason for the wr ong behaviour of the program. #include <stdio.h> #define PrintInt(expr) printf("%s : %d\n",#expr,(expr)) int FiveTimes(int a) { int t; t = a<<2 + a; return t; } int main() { int a = 1, b = 2,c = 3; PrintInt(FiveTimes(a)); PrintInt(FiveTimes(b)); PrintInt(FiveTimes(c)); return 0; } 24.Is the following a valid C program? #include <stdio.h> #define PrintInt(expr) printf("%s : %d\n",#expr,(expr)) int max(int x, int y) { (x > y) ? return x : return y; } int main() { int a = 10, b = 20; PrintInt(a); PrintInt(b); PrintInt(max(a,b)); } 25) #include<stdio.h> unsigned getbits(unsigned a,int i,int j) { return(a>>(i+1-j)) & ~(~0<<j); } main() { unsigned num=128; printf("%d\n",getbits(num,7,5)); } 26.#include<stdio.h> #define concatinate(a,b) a##b #define same1(a) #a #define same2(a) same1(a) main() { printf("%s\n",same2(concatinate(1,2))); printf("%s\n",same1(concatinate(1,2))); }

27.#include<stdio.h> #define sq(x) x*x main() { int a=5; printf("%d\n",sq(a+5)); } 28) #include <stdio.h> #define f(x,y) x##y #define g(x) #x #define h(x) g(y) int main() { printf("%s\n",h(f(2,3))); printf("%s\n",g(f(2,3))); return 0; } 29) #include <stdio.h> #define PrintInt(expr) printf("%s : %d\n",#expr,(expr)) int Shiftfn(int a) { int t; t = a<<2 + a; return t; } int main() { int i = 1, j = 2,k = 3; PrintInt(Shiftfn(i)); PrintInt(Shiftfn(j)); PrintInt(Shiftfn(k)); } 30) #include<stdio.h> int array[]={1,2,3,4,5,6,7,8}; #define SIZE (sizeof(array)/sizeof(int)) int main() { printf("%d",SIZE); if(-1<=SIZE) printf("1"); else printf("2"); return 0; } 31.#include <stdio.h> #define MAXI 100 main(){ int x=6,done,i; done=i=0;

do { if((x/=2)>1) {i++; continue;} else done++; }while ((i < MAXI) && !done); printf("%d %d\n",i,done); } Ans: 32) #include <stdio.h> #define DESHAWCURRENTDEBUGLEVEL 1 void main(void) { int i = 10 ; int j = 15 ; #ifdef DESHAWCURRENTDEBUGLEVEL printf("%d\n",i); #else printf("%d\n",j); #endif } Ans:10 33.#include <stdio.h> #define DEBUG(args) (printf("DEBUG: "), printf args) main() { int n = 10; if(n != 0) DEBUG(("n is %d\n", n)); } 34) #include <stdio.h> #define MAXI 100 main(){ int done,i,x=6; done=i=0; for(i = 0; (i< MAXI) && (x/=2)>1; i++) done++; printf("%d %d\n",i,done); } 35.#include <stdio.h> #define MAX(x,y) (x) >(y)?(x):(y) main() { int i=10,j=5,k=0; k= MAX(i++,++j); printf("%d..%d..%d",i,j,k); } ans:11,6,11

36.#include <stdio.h> #define PRINTIFLESS(x,y) if((x) < (y)) printf("First is smaller");else main() { int i = 2, k =1; if(i>0 && k>0) PRINTIFLESS(i,k); else printf("Numbers not greater than 0\n"); } 37.#include <stdio.h> #define PR(a) printf("a = %d\t",(int) (a)); #define PRINT(a) PR(a); putchar(\n); #define FUDGE(k) k + 3.14 main() { int x = 2; PRINT( x * FUDGE(2)); } Ans:7 38.#include <stdio.h> #define PRINT(int) printf( "int = %d ", int) main() { int x=03,y=02,z=01; PRINT (x | y & ~z); PRINT (x & y && z); PRINT (x ^ (y & ~z)); } 39.#include <stdio.h> #define PR(a) printf("%d\t",(int) (a)); #define PRINT(a,b,c) PR(a);PR(b);PR(c); #define MAX(a,b) (a<b?b:a) main(){ int x = 1,y = 2; PRINT(MAX(x++,y),x,y); PRINT(MAX(x++,y),x,y); } 40.Advantages of a macro over a function? Macro gets to see the Compilation environment, so it can expand __ __TIME__ __FI LE__ #defines. It is expanded by the preprocessor. For example, you cant do this without macros #define PRINT(EXPR) printf( #EXPR =%d\n, EXPR) PRINT( 5+6*7 ) // expands into printf(5+6*7=%d, 5+6*7 ); You can define your mini language with macros: #define strequal(A,B) (!strcmp(A,B)) Macros are a necessary evils of life. The purists dont like them, but without i t no real work gets done.

Files

1.In Header files whether the functions are declared or defined? Ans:-decleration statements only. 1.1fgets and gets which function is safe? Ans:-line at- time input is provided by the following two functions #include<stdio.h> char *fgets(char *restrict buf,int n,file *restrict fp); char *gets(char *buff); Both return :buf if ok, NULL on end of files or error. Both specify the address of the buffer to read the line into. The gets()function reads from standard inputs,whereas fgets() reads from the specified stream. With fegts(),we have to specify the size of the buffer ,n. this function reads u p through and including the next newline,but no more than n-1 charaters,into the buffer.the buffer is terminated with a null byte.If the line,including the term inating newline,is longer than n-1,only a partial line is returned ,but the buff er is always null terminated. The gets() function should never be used. The problem is that it doesnt allow th e caller to specify the buffersize.this allows the buffer to overflow if the lin e is longer than the buffer,writing over whatever happens to follow the buffer i n memory. 2.How can we read/write structures from/to data files? Ans:- example program which explains how to read /write structures from /to file s #include<stdio.h> int main() { struct employee { char name[20]; int age; }; struct employee e={raju,24}; FILE *fp ; Fp=fopen(employee,wb); fp=fwrite(&e,sizeof(e),1,fp) fclose(fp); return(0); } 3.What is Object file ? How can we access object file? Ans:-object file is also called as Binary I/O . 4.Which header file should you include if you are to declare a function which ca n accept variable number of arguments? Ans:- stdarg.h is the header file which should be included to accept variable n o of arguments. 5.How can you write a function similar to printf()? Ans:-17.24 in test your c skills 6.How can a called function determine the number of arguments passed to a variab le argument list function? Ans:-it cannot.any function that takes a variable number of arguments must be ab le to determine the number of arguments from the arguments themselves.for exampl

e,the printf() function does this by lowering for format specifier (%d etc) in t he format string.this is the reason why such functions fail badly if there is am ismatch in the format specifier and the argument list. If the arguments passed are all of the same type we can pass a sentinel val ue like -1 or 0 or NULL pointer at the end of the variable argument list .Altern atively we can also pass the count of number of variable arguments. 7.Can there be atleast some solution to determine the number of arguments passed to a variable argument list function? Ans:-if the arguments passed are all of the same type we can pass a sentinel val ue like -1 or 0 or NULL pointer at the end of the variable argument list.alterna tively we can also oass the count of number of variable arguments. 8.How can I open a file so that other programs can update it at the same time? Ans:-we can open a file with executable permissions so other programs can upda te at the same time. 9. getc,getch,getche,getchar? Ans:-getc and getchar are the two functions that allow to read one character at a time Syntax:#include<stdio.h> #include<curses.h> int getc(FILE *fp); int getch(void); int getchar(void); //curses from termin al keyboard. Getc and getchar reads the next character from file pointer and returns it as a n unsigned char cast to an int,or EOF or end of file or error. Getch reads a character from the window .it has two modes 1.delay mode 2.non-del ay mode. 10.gets,fgets? Ans:-refer q no 1.1 11.puts,fputs? Ans:-Line at a time output is provided by fputs and puts. #include<stdio.h> int fputs(cont char *restrict str,FILE *restrict fp); int puts(const char *str); both return:Non negative value if ok,EOF on error. The function fputs writes the null terminated string to the specified stream.The null byte at the end is not written.Note that this need not be line at a time o utput,since the string need not contain a newline as the last null character.Usu ally,this is the case the last non null character is a newline its not required. The puts function writes the null terminated string to the standard Output ,wi thout writing the null Byte.But puts then writes a newline character to standard output. The puts function is not unsafe ,like its counter part gets.Nevertheless ,well a void using it ,to prevent having to remember whether it appends a newline.If we use fgets and fputs,we know that we always have to deal with the new line charac ter at the end of each line. 12. Difference between scanf and fgets w.r.t strings? Ans:-scanf is a standard input where as fgets reads a line at a time from the sp ecified stram. 13. fseek( ),fread( ),fcntl( ),ftell( ) ? Ans:-ftell() Syntax:long ftell(FILE *fp); Return :current file position indicator of ok,-1 on error. For a binary file,a file position indicator is measured in bytes from the beginn

ing of th filr.The value returned by ftell for a binary file is byte position. fseek() syntax: int fseek(FILE *fp,long offset,int whence); returns :0 on ok,non zero on error to position a binary file using fseek,we must specify a byte offset an d how that ffset is interpreted.the values for whence are the lseek function SEEK_SET means from the beginning of the file SEEK_CUR means from the current file position SEEK_END means from the end of the file. Both ftell and fseek are used for positioning a stream. Fread(); Syntax:fread(void *restrict ptr,suze_t size,size_t nobj,FILE *restrict fp); Return :no of objects read. fread returns the no of objects read.for the read case this no can be less than object fread is used to read the entire structure at a time.whrere as getc(),fgetc() a re used to read one character at a time.whereas fgets() gets() are used to read one line at atime. fcntl() the fcntl function is used to change the properties of a file that is alrea dy open. Syntax: #include<fcntl.h> int fcntl(int filedes,int cmd,/* int any */) returns:depends on command. Th fcntl function is used for five different purposes 1.duplicate an exsisting descriptor(cmd=F_DUPFD) 2.get/set file descriptor flags(cmd=F_GETFD or F_SETFD) 3.get/set file status flags(cmd=F_GETFL or F_SETFL) 4.get/set asynchronous i/o ownership(cmd=F_GETOWN or F_SETOWN) 5.get/set record locks(cmd=F_GETLK or F_SETLK) 14. Can you use the function fprintf( ) to display the output on the screen ? Ans:-the function fprintf()writes output to the given output stream(i ,e files) 15.Difference between fprintf,sprintf and printf ? Ans:-syntax; int printf(cont char *format,) int fprintf(FILE *stream,const char * format,) int sprintf(char *,cont char *format ,) the function printf() writes output to standard output stram(stdout) the function fprintf() writes output to given output stream(files) the function sprintf() writes to character string str. 16.Difference between fsacnf,sscanf and scanf? Ans:-syntax: #include<stdio.h> int scanf(cont char *format,.) int fscanf(FILE *stram,const char *format,..); int sscanf(const char *str,const char *format,); the scanf() function reads input from the standard stream stdin. The fscanf() function reads input from the stream pointer stream. The sscanf() function reads its input from the character pointed to by str. 1. How can I increase the allowable number of simultaneously open files? 2. Whats wrong with the call fopen(c:\newdir\file.dat, r)?

3.The following is a small C program split across files. What do you expect the output to be, when both of them compiled together and run? File1.c int arr[80]; File2.c extern int *arr; int main() { arr[1] = 100; return 0; } Ans:the code will result in segmentation fault. 4.#include <stdio.h> main() { FILE *fp1,*fp2; fp1 = fopen("one","w"); fp2 = fopen("one","w"); fputc(A,fp1); fputc(B,fp2); fclose(fp1); fclose(fp2); } 5.#include <stdio.h> #define MAX 20 main() { FILE *fp1, *fp2; char *this1, *this2; fp1 = fopen("ip1.dat","r"); if(fp1==NULL)printf("file open error\n"); fp2 = fopen("ip2.dat","r"); if(fp2==NULL)printf("file open error\n"); if((getline(this1,fp1)!=0) && (getline(this2,fp2)!=0)){ if(strcmp(this1,this2)) continue; else { printf("lines do not match\n"); break;} } } int getline(char *line, FILE *fp) { if(fgets(line,MAX, fp) == NULL) return 0; else return strlen(line); } 6.#include <stdio.h> main() { FILE *fp; fp = fopen("testbuf.txt", "wt"); fwrite("1. This is fwrite\n",1, 18, fp); write(fileno(fp), "2.This is write\n", 17); fclose(fp); }

Loops: 1.The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesnt work. #include <stdio.h> int main() { int i; int n = 20; for( i = 0; i < n; i-- ) printf("-"); return 0; } Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above code, by changing exactly one character. There are th ree known solutions. See if you can get all those three. 2) #include<stdio.h> main() { int i=4; printf("%d %d %d",++i,i++,i*i); printf("\n"); printf("%d %d %d",i*i,++i,i++); } Ans:6 4 16 64 8 6 3)#include <stdio.h> main() { int i=4,j=2,k=0; char c1=a,c2=b; if(k==0)printf("k is zero\n"); else if(j==2)printf("j is 2\n"); else if(i==4)printf("i is 4\n"); if(c1!=a)printf("c1 is not a\n"); else if (c2==a)printf("c2 is b"); else printf("Hello\n"); } 4. What is the output of the program given below #include<stdio.h> main() { char i =0; for(;i >=0; i++) ; printf("%d\n", i ); } Ans: -128 5.main() { unsigned int i=65000; while(i++!=0); printf("%d",i);

} Answer: 1 Explanation: Note the semicolon after the while statement. When the value of i becomes 0 it c omes out of while loop. Due to post-increment on i the value of i while printing is 1. 6.main() { unsigned char i=0; for(;i>=0;i++) ; printf("%d\n",i); } Answer infinite loop Explanation The difference between the previous question and this one is that the char is de clared to be unsigned. So the i++ can never yield negative value and i>=0 never becomes false so that it can come out of the for loop. 7.What is the output of the following program? #include <stdio.h> #include <stdlib.h> #define SIZEOF(arr) (sizeof(arr)/sizeof(arr[0])) #define PrintInt(expr) printf("%s:%d\n",#expr,(expr)) int main() { /* The powers of 10 */ int pot[] = { 0001, 0010, 0100, 1000 }; int i; for(i=0;i<SIZEOF(pot);i++) PrintInt(pot[i]); return 0; } 8.What is the output of the following program? #include <stdio.h> int main() { int cnt = 5, a; do { a /= cnt; } while (cnt --); printf ("%d\n", a); return 0; } 9.#include <stdio.h> main() { char input[] = "SSSWILTECH1\1\1"; int i, c; for ( i=2; (c=input[i])!=\0; i++){

} Ans: switch s 10.#include <stdio.h> main() { int a,b,c; for (b=c=10;a= "Love Your INDIA \ TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq TNn* RPn/QPbEWS_JSWQAIJO^NBELP\ eHBFHT}TnALVlBLOFAKFCFQHFOQIAIREETMSQGCSQOU HATFAJKSbEALGSkMCSlOASn^r\ ^r\\tZvYxXyT|S~Pn SPm SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"[b+++6];) while(a-->64) putchar (++c==Z?c=c/9:33^b&1); } 11.#include <stdio.h> main() { unsigned int i=1; for(;i>=0;i--) printf("hello: %u\n",i); } ans:infinite loop will be executed. 12.#include <stdio.h> #include<math.h> //#define sqrt(x) (( x < 0) ? sqrt(-x) : sqrt(x)) main() { int y; y = sqrt(-9); printf("%d",y); } Ans:sqrt is defined for negative numbers in math library 13.#include <stdio.h> main() { char int do{ as[] = "\\0\0"; i = 0; switch( as[i++]){ case \\ : printf("A"); break; case 0 : printf("B"); break; default : printf("C");

switch(c){ case a: putchar (i); continue; case 1: break; case 1: while (( c = input[++i]) != \1 && c!= \0); case 9: putchar(S); case E: case L: continue; default: putchar(c);continue; } putchar( ); } putchar(\n);

break; } } while(i<3); } 14) #include <stdio.h> #define MAXI 100 main(){ int done,i,x=6; done=i=0; while (i < MAXI && !done){ if ((x/=2)>1){ i++; continue;} done++; } printf("%d %d\n",i,done); }

Command Line aruguments: 1.What do c and v in argc and argv stand for? Ans:- count of arguments and vector (array) of arguments 2.Are the variables argc and argv are are local to main()? Ans :- yes 3.What is the maximum combined length of command line arguments including the space between adjacent arguments? Ans:-it may vary one operating system to other. 4.If we want that any wildcard character in the command line arguments should be appropriately expanded are we required to make any special provision? If yes which? Ans:-yes ,compile the program as tcc myprog wildargs .obj This compiles the file myprog.c and links it with the wild card expansion module WILDARGS.obj.then run the resulting executable file MYPROG.exe If you want the wild card expansion to be default ,so that you wont have to link your program explicitly with WILD ARGS.obj you can modify your standard .LIB li brary files to have WILDARGS,obj linked automatically.to achieve this we have to remove SETARGV from the library and add WILDARGS Under linux and unix the shell expands the wild card characters before passing t hem to main().for example ,if we execute the program as shown below Myprog *.c Then all file names with .c extension would be passed to main() as command line arguments 5.Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function? Ans:-yes,using the predefined variables argc, -argv.this is a compiler dependent feature.it works in tc/tc++ but not in gcc or visual studio 6.Uses of command line arguments? Ans:-c begins every program with a call to main().some times you will want to pa ss the information into a program ahen you run it.this is generally found by pas

sing command line arguments to main().c defines two optional features to main(). they are argc and argv argc will always be atlaest 1 because the name of the pro gram qualifies one argument 7.#include <stdio.h> main(int sizeofargv, char *argv[]) { while(sizeofargv) printf("%s ",argv[--sizeofargv]); } Ans:./a.out . Function Pointers 1.An array of 3 pointers to chars Ans:- char *pa[3] 3.A pointer to array of 3 chars Ans:- char a[]={3,4,5} char *pa =&a; 4.A pointer to function which receives an integer pointer and returns a float po inter. Ans:-float *myfunc(int *,int *); 5.A pointer to function which receives nothing and returns a nothing. Ans:-void *myfunc(void); Miscellaneous 1.Interchange 2 variables without using third variable? Method 1: a=a+b; b=a-b;a=a-b; Method 2: a=a^b; b=a^b; a=a^b; Method 3: A=(a+b)-(b=a); 2.Write a macro to find greatest/smallest of 3 numbers? #define MAX(a,b,c) (a>b)?(a>c)?a:c:(b>c)?b:c; #define MIN(a,b,c) (a<b)?(a<c)?a:c:(b<c)?b:c; 3.Sizeof("length")? 7(including NULL character) 4.Strlen("length")? 6(excluding NULL character) 5.Examples of recursion? Ans:- recursion is aprocess by which a function calls itself repeatedly until so me specified condition has been satisfied.ex:ref 6 6.Factorial of number? Ans:-function to find factorial of a given number. int factorial(int n) { If(n==1) Return 1; Return (n*factorial(n-1)); } 7.Fibonacci series? 8.What the functions atoi(),itoa(),gcvt()do? 9.Does there exist any other function which can be used to convert an integer ( or) a float to a string ? 10.memcpy( ),memset( ),memmove( ) ? 11.Difference between memmove( ) and memcpy( ) ?

12.fseek( ),fread( ),fcntl( ),ftell( ) ? 13.Can you use the function fprintf( ) to display the output on the screen ? 15.What is volatile ? 16.Difference between fprintf,sprintf and printf ? 17.Difference between fsacnf,sscanf and scanf? 18.What is const qualifier ? 19.Difference between declarations and definitions? 20. Little endian and big-endian? 21. How to find whether the machine is following little endian or big endian? 22.Types of errors and when they will arise? 23.How to reduce the final size of executable ? 24. who will call the main function? C Start -up function 25.why static variables are initialized only once? 26.How can we view the contents of a header file? 27.What is more efficient, a switch statement or an if-else statement? 28.Difference between #include<stdio.h> and #include"stdio.h"?

29 If( ? ) { Printf(hello); } Else { Printf(world); } Ans helloworld 30 shifting the n bits to a[10] General Questions: 1. Differentiate between a linker and linkage? A linker converts an object code into an executable code by linking toget her the necessary build in functions. The form and place of declaration where the variable is declared in a program de termine the linkage of variable. 2. What is the difference between goto and longjmp() and setjmp()? A goto statement implements a local jump of program execution, and the longjmp( ) and setjmp() functions implement a nonlocal, or far, jump of program execution . Generally, a jump in execution of any kind should be avoided because it is not c onsidered good programming practice to use such statements as goto and longjmp i n your program. A goto statement simply bypasses code in your program and jumps to a predefined position. To use the goto statement, you give it a labeled position to jump to. This predefined position must be within the same function. You cannot implement gotos between functions. When your program calls setjmp(), the current state of your program is saved in a structure of type jmp_buf. Later, your program can call the longjmp() function to restore the programs state as it was when you called setjmp().Unlike the goto statement, the longjmp() and setjmp() functions do not need to be implemented i

n the same function. However, there is a major drawback to using these functions: your program, when restored to its previously saved state, will lose its references to any dynamica lly allocated memory between the longjmp() and the setjmp(). This means you will waste memory for every malloc() or calloc() you have implemented between your l ongjmp() and setjmp(), and your program will be horribly inefficient. It is high ly recommended that you avoid using functions such as longjmp() and setjmp() bec ause they, like the goto statement, are quite often an indication of poor progra mming practice. 3. What is modular programming? If a program is large, it is subdivided into a number of smaller program s that are called modules or subprograms. If a complex problem is solved usi ng more modules, this approach is known as modular programming. 4. How many levels deep can include files be nested? Even though there is no limit to the number of levels of nested include files yo u can have, your compiler might run out of stack space while trying to include a n inordinately high number of files. This number varies according to your hardwa re configuration and possibly your compiler. 5.What is the difference between NULL and NUL? NULL is a macro defined in for the null pointer. #define NULL (void *) 0 NUL is the name of the first character in the ASCII character set. It correspond s to a zero value. Theres no standard macro NUL in C, but some people like to def ine it. #define NUL (void)0 6.What is the difference between a string copy (strcpy) and a memory copy (memcp y)? When should each be used? The strcpy() function is designed to work exclusively with strings. It copies ea ch byte of the source string to the destination string and stops when the termin ating null character () 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 nul l character, you must provide the memcpy() function with the number of bytes you want to copy from the source to the destination. 7.Is it possible to execute code even after the program exits the main() functio n? The standard C library provides a function named atexit() that can be used to pe rform cleanup operations when your program terminates. You can set up a set of f unctions you want to perform automatically when your program exits by passing fu nction pointers to the at exit() function. 8.Why n++ executes faster than n+1? The expression n++ requires a single machine instruction such as INR to carry ou t the increment operation whereas; n+1 requires more instructions to carry out t his operation. 9.Write the equivalent expression for x%8? x&7 10.Can a variable be both const and volatile? Yes. The const modifier means that this code cannot change the value of the vari able, but that does not mean that the value cannot be changed by means outside t

his code. For instance, in the example in FAQ 8, the timer structure was accesse d through a volatile const pointer. The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardw are on the computer, so it was declared volatile. If a variable is both const an d volatile, the two modifiers can appear in either order. 11.How to reduce a final size of executable file? Size of the final executable can be reduced using dynamic linking for libraries. 12. How do you write a program which produces its own source code as its output? Ans:we can produce the source code of the same input as its output by using comm and line arguments and providing file name as an argument. 13. How can I find the day of the week given the date? 14. How do I access command-line arguments? 15. How can I invoke another program from within a C program? Ans:By using family of exec functions or by using system() system call we can invo ke another program with in a c program. Ex: #include<stdio.h> #include<unistd.h> main() { const char *command="./ex52"; int i=98765; printf("%d\n",printf("%d",printf("%d",i))); system(command);/execvp(command ,NULL) return 0; } Output of the above program will display both programs outputs. Ex52.c file #include<stdio.h> main() { char c; while(c=getchar()!=a)printf("%d",c); } //INPUT=dcba Output :111 Output of above example is: 9876551 111 16. How can I find out how much memory is available? 17. How can I read a directory in a C program? 18.main() { printf("\nab"); printf("\bsi"); printf("\rha"); } Answer: hai Explanation: \n - newline \b - backspace

\r - linefeed Unix Questions: 1. After compiling a c program in UNIX using gcc compiler the executable file wi ll be a) a.out Ans: a b) a.exe c) a.bat

2. In UNIX the commands like date, cat, ls etc., are present in a)/dev b) /bin and /usr/bin c) /etc d) /tmp Ans: b Process: 1. what is the ouput of the following program main() { int i=2; if(0==fork()) { i+=2; } else { wait(0); printf("%d",i); } } a) i+=2 is executed only by child b) i+=2 is executed only by parent Ans: a 2.what is the output of the following program. int main() { printf("Hello"); fork(); printf("World"); } Ans: Hello World world 3.#include <stdio.h> main() { printf("hello"); fork(); } Ans:hello hello will be printed on the screen .one in child context.other in par ent context. 4.What is the output of the following program #include<stdio.h> main() { int i=0; fork(); printf("%d",i++);

fork(); printf("%d",i++); fork(); wait(); } Ans: 0101010101010101 ENUMERATIONS: 1.What is the benefit of using an enum rather than a #define constant? 1. Lower maintenance requirement 2. Improved program readability 3. enums have better debugging capability than #define, because most debuggers c annot print #define values, you would most likely have to search for that value by manually looking it up in a header file. 4. Another advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values b y the programmer. For instance, if you had an enumerated constant type for error codes that could occur in your program, your enum definition could look something like this: enum Error_Code { OUT_OF_MEMORY, INSUFFICIENT_DISK_SPACE, LOGIC_ERROR, FILE_NOT_FOUND }; In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0 (zero) by the compiler because it appears first in the definition. The compiler then continues to automatically assign numbers to the enumerated constants, mak ing INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and FILE_NOT_FOU ND equal to 3, so on. If you were to approach the same example by using symbolic constants, your code would look something like this: #define #define #define #define OUT_OF_MEMORY 0 INSUFFICIENT_DISK_SPACE 1 LOGIC_ERROR 2 FILE_NOT_FOUND 3

2.What is the output of the following program ?why? Enum{false,true}; int main() { int i=1; do { printf("%d\n",i); i++; if(i < 15) continue; }while(false); return 0; } Ans:the program will print 1.as the loop is executed only once.we have placed fa lse as an enumeration constant it will take 0.as the value of false is 0 loop is terminated as soon as it comes out of the loop for the first time.

3.#include <stdio.h> main() { enum _tag{ left=10, right, front=100, back}; printf("left is %d, right is %d, front is %d, back is %d",left,right,front,back ); } Ans:left is 10,right is 11,front is 100,back is 101. OPERATIONS: 1.What will be printed as the result of the operation below: main() { int x=20,y=35; x=y++ + x++; y= ++y + ++x; printf(%d%d\n,x,y); } Answer: x=57,y=94 2. How can I convert integers to binary or hexadecimal? Ans :we can convert a given integer into binary or hexa decimal l by dividing th e given number by 2 for binary and 16 for hexadecimal,and taking the remainders ij the reverse order of division. 3.main() { float me = 1.1; double you = 1.1; if(me==you) printf("I love U"); else printf("I hate U"); } Answer: I hate U Explanation: For floating point numbers (float, double, long double) the values cannot be pre dicted exactly. Depending on the number of bytes, the precession with of the val ue represented varies. Float takes 4 bytes and long double takes 10 bytes. So f loat stores 0.9 with less precision than long double. Rule of Thumb: Never compare or at-least be cautious when using floating point numbers with rel ational operators (== , >, <, <=, >=,!= ) . 4.main() { int i=-1,j=-1,k=0,l=2,m; m=i++&&j++&&k++||l++; printf("%d %d %d %d %d",i,j,k,l,m); } Answer: 0 0 1 3 1 Explanation : Logical operations always give a result of 1 or 0 . And also the logical AND (&& ) operator has higher priority over the logical OR (||) operator. So the express ion i++ && j++ && k++ is executed first. The result of this expression is 0 (1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR

operator always gives 1 except for 0 || 0 combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1. 5.main() { int i = 3; for (;i++=0;) printf(%d,i); } Answer: Compiler Error: Lvalue required. Explanation: As we know that increment operators return rvalues and hence it cannot appear o n the left hand side of an assignment operation. 6.main() { int i=5; printf("%d%d%d%d%d%d",i++,i--,++i,--i,i); } Answer: 45545 Explanation: The arguments in a function call are pushed into the stack from left to right. T he evaluation is by popping out from the stack. and the evaluation is from righ t to left, hence the result. 7.void main() { int i=5; printf("%d",i++ + ++i); } Answer: Output Cannot be predicted exactly. Explanation: Side effects are involved in the evaluation of i 8.main() { char *p; int *q; long *r; p=q=r=0; p++; q++; r++; printf("%p...%p...%p",p,q,r); } Answer: 0001...0004...0004 Explanation: ++ operator when applied to pointers increments address according to their corr esponding data-types. 9.main() { char *p; p="%d\n"; p++; p++; printf(p-2,300);

} Answer: 300 Explanation: The pointer points to % since it is incremented twice and again decremented by 2 , it points to %d\n and 300 is printed. 10.void main() { int i=i++,j=j++,k=k++; printf(%d%d%d,i,j,k); } Answer: Garbage values. Explanation: An identifier is available to use in program code from the point of its declarat ion. So expressions such as i = i++ are valid statements. The i, j and k are automat ic variables and so they contain some garbage value. Garbage in is garbage out ( GIGO). 11.main() { float f=5,g=10; enum{i=10,j=20,k=50}; printf("%d\n",++k); printf("%f\n",f<<2); printf("%lf\n",f%g); printf("%lf\n",fmod(f,g)); } Answer: Line no 5: Error: Lvalue required Line no 6: Cannot apply leftshift to float Line no 7: Cannot apply mod to float Explanation: Enumeration constants cannot be modified, so you cannot apply ++ . Bit-wise operators and % operators cannot be applied on float va lues. fmod() is to find the modulus values for floats as % operator is for ints 12) void main() { if(~0 == (unsigned int)-1) printf(You can answer this if you know how values are represented in memory); } Answer You can answer this if you know how values are represented in memory Explanation ~ (tilde operator or bit-wise negation operator) operates on 0 to produce all on es to fill the space for an integer. 1 is represented in unsigned value as all 1s and so both are equal. 13.main() { char *p = ayqm; printf(%c,++*(p++)); } Answer: b 14) main() {

int i=5; printf("%d",++i++); } Answer: Compiler error: Lvalue required in function main Explanation: ++i yields an rvalue. For postfix ++ to operate an lvalue is re quired. 15.main() { int i=5; printf(%d,i=++i ==6); } Answer: 1 Explanation: The expression can be treated as i = (++i==6), because == is of higher precedenc e than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence the result. 16)Which expression always returns true and which expression always returns fals e? 17) #include <stdio.h> main() { int p; for(p = 1; p<=10,--p; p=p+2) puts("Hello"); } 18.#include <stdio.h> main() { int x,y=1,z; if(x=z=y); x = 3; printf("%d %d %d\n",x,y,z); while (y<4) x+=++y; printf("%d %d\n",x,y); } Ans: 19) #include<stdio.h> main() { char c=6; int d=6; printf("%d %d %d",d,d+=c>0&&c<=7,c++); } Ans: 7,7,54 20.#include <stdio.h> main() { int i ; i = 1; i= i+2*i++; printf("i is now %d",i);

} ans:4 21) #include<stdio.h> main() { int a=4,b=2; a=b<<a + b>>2; b=b<<a + b>>2; printf("%d %d",a,b); } Ans: 32,2 Note:when we left shift any number 32 times it results in the same number. 22.#include <stdio.h> main() { int a = 0xff; if(a<<4>>12) printf("Right"); else printf("Wrong"); } Ans:wrong 23.#include <stdio.h> main() { int I =-3, j=2, k = 0,m; m = ++I && ++j && ++k; printf("\n%d %d %d %d", I, j, k, m); } ans:-2 3 1 1 Simple Input Output: 1.What would be the output of the following C program? (Is it a valid C program? ) #include <stdio.h>0 int main() { int i=43; printf("%d\n",printf("%d",printf("%d",i))); return 0; } Ans:the output of the following program will be 4321.the printf statements are e xecuted in the clock wise direction.printf returns the no of characters returned by the function.so the first printf prints 43.second will print 2 and third wil l print 1. 2) #include<stdio.h> main() { int i=98765; printf("%d\n",printf("%d",printf("%d",i))); } ans:9876551 3.#include <stdio.h> #define scanf "%s DE Shaw" main() {

printf(scanf,scanf); } 4.) #include<stdio.h> main() { char c; while(c=getchar()!=a)printf("%d",c); } //INPUT=dcba Ans:111 5) #include<stdio.h> main() { int a=1,b=3,c,d; c=(a,b); d=a,b,c; printf("%d %d",c,d); } Ans:3,1 6) #include <stdio.h> int main() { int i; i = 10,20,30; printf("i:%d\n",i); } Ans: I value is 10. 7.#include <stdio.h> main() { char a,b,c; scanf("%c %c %c",&a,&b,&c); printf("%c %c %c ", a, b, c); } Ans:if input is a b c output will be a b c 8.#include <stdio.h> main() { int a = 10000; char b=c; int i,j; printf("%d,%d",printf("%d\n",a),printf("%c\n",b)); } Ans: c 100000 6,2 9) #include<stdio.h> main() { int x; x=20; printf("x:%d\n",x); printf("sizeof(x++) is: %d\n",sizeof(x++)); printf("x:%d\n",x);

} ans:20,4,20 10.#include <stdio.h> main() { int x; x = printf("%d\n",x=printf("%d\n",100)); printf("%d\n",x); } ans:100 4 2 11) #include <stdio.h> main() { int i; char c; for (i=0;i<5;i++){ scanf("%d",&c); printf("%d",i); } } 12.What will be printed out when the following code is executed: main() { printf("%x",-1<<4); } Ans:fffffff0 13.main() { int c=- -2; printf("c=%d",c); } Answer: c=2; Explanation:Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus. 14. main() { int i; printf("%d",scanf("%d",&i)); // value 10 is given as input here } Answer: 1 Explanation: Scanf returns number of items successfully read and not 1/0. Here 10 is given a s input which should have been scanned successfully. So number of items read is 1. 15.What are returned by printf(), scanf() functions,if they return anything mean s what are that? Return type of printf() and scanf() is integer. scanf() returns the no.of variab les used and printf() returns the total no.of bytes. return type of scanf and printf is int scanf returns no of valid inputs you are getting inside it printf returns no of characters as well as formatspecifier inside it 16.#include <stdio.h>

#include <unistd.h> int main() { while(1) { fprintf(stdout,"hello-out"); fprintf(stderr,"hello-err"); sleep(1); } return 0; } Ans:in this hello-out is not printed even though it present in stdout.because st derr has higher priority.the contents in the stderr are given to the processor a s soon as they are available.this is the reason why we will get hello_err. 17.I thought the following C program is perfectly valid (after reading about the comma operator in C). But there is a mistake in the following program, can you identify it? #include <stdio.h> int main() { int a = 1,2; printf("a : %d\n",a); return 0; } Ans :1 18.The following is a simple c program, in which there is a function called Erro r to display errors. Can you see a potential problem with the way Error is defin ed? #include <stdlib.h> #include <stdio.h> void Error(char* s) { printf(s); return; } int main() { int *p; p = malloc(sizeof(int)); if(p == NULL) { Error("Could not allocate the memory\n"); Error("Quitting....\n"); exit(1); } else { /*some stuff to use p*/ } return 0; } 19.What is the differnce between the following function calls to scanf?(Please n otice the space carefully in the second call. Try removing it and observe the be haviour of the program) #include<stdio.h> int main() {

int i,j; scanf(%d %d,&i,&j); printf(value of I is %d\n,i); } Ans: 20.What is the potential problem with the following C program? #include <stdio.h> int main() { char str[80]; printf("Enter the string:"); scanf("%s",str); printf("You entered:%s\n",str); return 0; } Ans: 21.What is the output of the following program? #include<stdio.h> int main() { int i; i = 10; printf("i : %d\n",i); printf("sizeof(i++) is: %d\n",sizeof(i++)); printf("i : %d\n",i); return 0; } Ans:the output of the following program is 4 .the printf returns the size of i.h ere the increment operation is performed on the variable only 22.What is the output of the following program? #include <stdio.h> int main() { int i; i = 1,2,3; printf("i:%d\n",i); return 0; } Ans:the output of the following program is 1. 23.Why does the following program give a warning? (Please remember that sending a normal pointer to a function requiring const pointer does not give any warning ) #include <stdio.h> void foo(const char **p) { } int main(int argc, char **argv) { foo(argv); return 0; } Ans: The following is a piece of code which implements the reverse Polish Calculator. There is a(are) serious(s) bug in the code. Find it(them) out!!! Assume that th e function getop returns the appropriate return values for operands, opcodes, EO F etc.. 24.#include <stdio.h> #include <stdlib.h> #define MAX 80 #define NUMBER 0

int getop(char[]); void push(double); double pop(void); int main() { int type; char s[MAX]; while((type = getop(s)) != EOF) { switch(type) { case NUMBER: push(atof(s)); break; case +: push(pop() + pop()); break; case *: push(pop() * pop()); break; case -: push(pop() - pop()); break; case /: push(pop() / pop()); break; /* ... * ... * ... */ } } } 25.The following is a simple program which implements a minimal version of banne r command available on most *nix systems. Find out the logic used in the program . #include<stdio.h> #include<ctype.h> char t[]={ 0,0,0,0,0,0,12,18,33,63, 33,33,62,32,62,33,33,62,30,33, 32,32,33,30,62,33,33,33,33,62, 63,32,62,32,32,63,63,32,62,32, 32,32,30,33,32,39,33,30,33,33, 63,33,33,33,4,4,4,4,4,4, 1,1,1,1,33,30,33,34,60,36, 34,33,32,32,32,32,32,63,33,51, 45,33,33,33,33,49,41,37,35,33, 30,33,33,33,33,30,62,33,33,62, 32,32,30,33,33,37,34,29,62,33, 33,62,34,33,30,32,30,1,33,30, 31,4,4,4,4,4,33,33,33,33, 33,30,33,33,33,33,18,12,33,33, 33,45,51,33,33,18,12,12,18,33, 17,10,4,4,4,4,63,2,4,8, 16,63 };

int main(int argc,char** argv) { int r,pr; for(r=0;r<6;++r) { char *p=argv[1]; while(pr&&*p) { int o=(toupper(*p++)-A)*6+6+r; o=(o<0||o>=sizeof(t))?0:o; for(pr=5;pr>=-1;--pr) { printf("%c",( ( (pr>=0) && (t[o]&(1<<pr)))?#: )); } } printf("\n"); } return 0; } 26.The following is the implementation of the Euclids algorithm for finding the G.C.D(Greatest Common divisor) of two integers. Explain the logic for the below implementation and think of any possible improvements on the current implementa tion. BTW, what does scanf function return? #include <stdio.h> int gcd(int u,int v) { int t; while(v > 0) { if(u > v) { t = u; u = v; v = t; } v = v-u; } return u; } int main() { int x,y; printf("Enter x y to find their gcd:"); while(scanf("%d%d",&x, &y) != EOF) { if(x >0 && y>0) printf("%d %d %d\n",x,y,gcd(x,y)); printf("Enter x y to find their gcd:"); } printf("\n"); return 0; }

27.Also implement a C function similar to the above to find the GCD of 4 integer s. The following is a simple C program to read a date and print the date. Run it an d explain the behaviour 28.#include <stdio.h> int main() { int day,month,year; printf("Enter the date (dd-mm-yyyy) format including -s:"); scanf("%d-%d-%d",&day,&month,&year); printf("The date you have entered is %d-%d-%d\n",day,month,year); return 0; } 29) #include <stdio.h> main() { int a = 10, b = 5,c = 3,d = 3; if ((a<b) && (c = d++)) printf(" %d %d %d %d ", a, b, c, d); else printf(" %d %d %d %d ", a, b, c, d); } 30.The following is a simple C program to read and print an integer. But it is n ot working properly. What is(are) the mistake(s)? #include <stdio.h> int main() { int n; printf("Enter a number:\n"); scanf("%d\n",n); printf("You entered %d \n",n); return 0; } 31.Is the following a valid C program? If so, what is the output of it? #include <stdio.h> int main() { int a=3, b = 5; printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]); printf(&a["WHAT%c%c%c %c%c %c !\n"], 1["this"], 2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]); return 0; } 32) #include <stdio.h> main() { int a,b; scanf("%d %d", &a, &b); printf("%d\n", a+++b); printf("%d %d\n",a,b);

Ans:4 5/9/5 5 33) #include <stdio.h> main() { printf(" %d\n",---+///); } 34) #include<stdio.h> main() { int x=5,p=10; printf("%*d",x,p); } ans:10 35) #include<stdio.h> int main(int k) { if(k<10) printf("%d ",main(k+1)); return k; } Ans:10 9 8 7 6 5 4 3 2 36.#include <stdio.h> main() { int a=10,b; b=a>=5?100:200; printf("%d\n",b); } Ans:100 37.#include <stdio.h> main() { int a; a = (1,45,012); printf("%d", a); } Ans:10 38.#include <stdio.h> main() { int x = 10,y=2,z; z=x/*y+y*/+y; printf("%d\n",z); } Ans:12 39.What does the format specifier %n of printf function do? 40.How do you print I can print % using the printf function? (Remember % is used as a format specifier!!!)

41.What is the format specifiers for printf to print double and float values?

DeclerationsAnd Definitions: 1.What is the difference between declaring a variable and defining a variable? Declaring a variable means describing its type to the compiler but not allocatin g any space for it. Defining a variable means declaring it and also allocating s pace to hold the variable. You can also initialize a variable at the time it is defined. 2.Is it acceptable to declare/define a variable in a C header? A global variable that must be accessed from more than one file can and should b e declared in a header file. In addition, such a variable must be defined in one source file. Variables should not be defined in header files, because the header file can be included in multiple source files, which would cause multiple definitions of the variable. The ANSI C standard will allow multiple external definitions, provide d that there is only one initialization. But because theres really no advantage to using this feature, its probably best to avoid it and maintain a higher lev el of portability. Global variables that do not have to be accessed from more than one file should be declared static and should not appear in a header file. 3..#include<stdio.h> main() { struct xx { int x=3; char name[]="hello"; }; struct xx *s; printf("%d",s->x); printf("%s",s->name); } Answer: Compiler Error Explanation: You should not initialize variables in declaration typedef enum errorType{warning, error, exception,}error; main() { error g1; g1=1; printf("%d",g1); } Answer Compiler error: Multiple declaration for error Explanation The name error is used in the two meanings. One means that it is a enumerator co nstant with value 1. The another use is that it is a type name (due to typedef) for enum errorType. Given a situation the compiler cannot distinguish the meanin g of error to know in what sense the error is used: error g1; g1=error; // which error it refers in each case? When the compiler can distinguish between usages then it will not issue error (i n pure technical terms, names can only be overloaded in different namespaces). Note: the extra comma in the declaration,

enum errorType{warning, error, exception,} is not an error. An extra comma is valid and is provided just for programmers con venience. 4) Declare an array of N pointers to functions returning pointers to functi ons returning pointers to characters? Answer: (char*(*)( )) (*ptr[N])( ); 5) main() { struct student { char name[30]; struct date dob; }stud; struct date { int day,month,year; }; scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month, & student.dob.year); } Answer: Compiler Error: Undefined structure date Explanation: Inside the struct definition of student the member of type struct date is given. T he compiler doesnt have the definition of date structure (forward reference is n ot allowed in C in this case) so it issues an error. 6.Is there any difference between the two declarations, 1.int foo(int *arr[]) and 1.int foo(int *arr[2]) Answer: No Explanation: Functions can only pass pointers and not arrays. The numbers that are allowed in side the [] is just for more readability. So there is no difference between the two declarations. 7) main() { struct student { char name[30]; struct date dob; }stud; struct date { int day,month,year; }; scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month, & student.dob.year); } Answer: Compiler Error: Undefined structure date Explanation: Inside the struct definition of student the member of type struct date is given. T he compiler doesnt have the definition of date structure (forward reference is n

ot allowed in C in this case) so it issues an error. 8.Is the following code legal? struct a { int x; struct a b; } Answer: No Explanation: Is it not legal for a structure to contain a member that is of the same type as in this case. Because this will cause the structure declaration to be re cursive without end. 9) Is the following code legal? struct a { int x; struct a *b; } Answer: Yes. Explanation: *b is a pointer to type struct a and so is legal. The compiler knows, the size o f the pointer to a structure even before the size of the structure is determined(as you know the pointer to any type is of same size). This type of structures is known as self-referencing structure. 10.Is the following code legal? typedef struct a { int x; aType *b; }aType Answer: No Explanation: The typename aType is not known at the point of declaring the structure (forward references are not made for typedefs). 11.Is the following code legal? typedef struct a aType; struct a { int x; aType *b; }; Answer: Yes Explanation: The typename aType is known at the point of declaring the structure, because it is already typedefined. 12.Is the following code legal? void main() { typedef struct a aType; aType someVariable; struct a {

int x; aType *b; }; } Answer: No Explanation: When the declaration, typedef struct a aType; is encountered body of struct a is not known. This is known as incomplete types. Switch Case: 1.main() { float i=1.5; switch(i) { case 1: printf("1"); case 2: printf("2"); default : printf("0"); } } Answer: Compiler Error: switch expression not integral 2.What is the out put of the following program #include <stdio.h> main() { char ch = A; while(ch <=F){ switch(ch){ case A:case B:case C: case D: ch++; continue; case E: case F: ch++; } putchar(ch); } } Ans:F G 3.#include<stdio.h> int main() { int a=10; switch(a) { case 1: printf("ONE\n"); break; case 2: printf("TWO\n"); break; defa1ut: printf("NONE\n"); } return 0; }

Ans:nothing will be printed here case 10 is not present and a default case is no t provided. 4) #include <stdio.h> main() { int i = 1; switch(i) { printf("\nHello, "); case 1: printf("One, "); i++; break; case 2: printf("Two"); break; } } Ans:One 5.void duff(register char *to, register char *from, register int count) { register int n=(count+7)/8; switch(count%8){ case 0: do{ *to++ = *from++; case 7: *to++ = *from++; case 6: *to++ = *from++; case 5: *to++ = *from++; case 4: *to++ = *from++; case 3: *to++ = *from++; case 2: *to++ = *from++; case 1: *to++ = *from++; }while( --n >0); } } Is the above valid C code? If so, what is it trying to acheive and why would any one do something like the above? 6.Explain the output of the following C program (No, the output is not 20). #include<stdio.h> int main() { int a=1; switch(a) { int b=20; case 1: printf("b is %d\n",b); break; default:printf("b is %d\n",b); break; } return 0; } ans:garbage value of b is printed in the above case. 7) #include <stdio.h> main() { int i=6,j=4; printf("NO\n"); switch(i)

{ do{ case 1: printf("yes\n"); case 2: case 3: case 4: case 5: case 6: j--; }while (j); } } Data Structures 1)How do we check whether a linked list is circular? 2)Which is the easiest sorting method? 3)Which is the quickest sorting method? 4)Which are the best sorting algorithms to sort a linked list? 5. which of the following is not a data structure a) stack b) queue c) tree d) none Ans: d Variable types: 1) #include<stdio.h> int main() { char c; c=255; printf("%d",c); return(0); } Ans:-1 2.#include <stdio.h> main() { unsigned int m[] = { 0x01,0x02, 0x04, 0x08,0x10, 0x20, 0x40, 0x80}; unsigned int n,i; printf("%d",m[7]); scanf("%d",&n); for(i=0;i<=7;i++) { if (n& m[i]) printf("\nyes"); else printf("\nno"); } }

Questions on C++ 1)Name some pure object oriented languages. Ans:some of the pure object oriented languages are java,C++,small talk,object Pa scal. 2)What is a container class? What are the different types of container classes? Ans: 3)What are the major differences between C and C++? 4)What is an incomplete type? 5)Is C a)A low level language b)A middle level language c)A high level language ? 6)Why doesnt C support function overloading?

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