Sei sulla pagina 1di 28

ANSWERS FOR TECHNICAL QUESTIONS IN C 1. What does static variable mean?

When a variable is declared to static it will be initialized the default value zero. It is local to the block in which it is declared. The lifetime persists for each and every function call. 2. What is a pointer? A pointer is also called a reference of a particular data type. But instead of storing some value it stores the address of a particular variable. This address can be initialized by using & operator. Eg: int a = &b; 3. What is a structure? Structure is a special type of user defined data structure which comprises of a collection of certain type predefined data types like int, char, float etc. It is an entity which comprises of many atoms. 4. What are differences between structure and array? Arrays are group of data of same data type, whereas structure is combination of entities of different data types. Size of array needs to be declared initially itself whereas structure can be done both initially and dynamically. 5. In header files whether functions are declared or defined? Inside header files the functions are defined and they are not declared. This is also a type of structure definition. 6. What are the differences between malloc() and calloc()? malloc() takes a single argument(memory required in bytes), while calloc() needs 2 arguments(number of variables to allocate memory, size in bytes of a single variable). Secondly, malloc() doesnot initialize the memory allocated, while calloc() initializes the allocated memory to ZERO. The difference b/w malloc and

calloc are: 1. malloc() allocates byte of memory where as calloc()allocates block of memory. 7. What are macros? What are its advantages and disadvantages? Macros are short form for macro definition. These macro names are handled by the pre processor and it replaces the corresponding definition. Macros increase the speed of execution whereas they also increase the size of the program. 8. Differences between pass by reference and pass by value Whenever we call a function if we pass the value of the variable with it, it is called call by value. Whereas, if we pass the address were the variable is stored it is called, call by reference. 9. What is static identifier? In C the names of variables, functions, labels etc are named as identifiers. Similarly static is also an identifier which is used to initialize value to some data types. 10. Where is the auto variables stored? Even if variables are not declared auto by default they are taken to be auto. When initialized auto variables are stored in the memory it is local to the block in which it is declared, its default value is garbage. 11. Where does global, static, local, register variables, free memory and c Program instructions get stored? Local Variables are stored in Stack. Register variables are stored in Register. Global & static variables are stored in data segment. The memory created dynamically are stored in Heap And the C program instructions get stored in code segment. 12. Difference between arrays and linked list? Arrays are initialized statically whereas linked list is initialized dynamically using pointers. Arrays are easy to create and use but creating linked list is tough. Arrays must be

contiguous memory locations but in linked list they can be at different places. 13. What are enumerations? Enumeration is the process by which we can declare what values a particular variable of a defined data type can take. 14. Describe about storage allocation and scope of global, extern, static, local and register variables? The extern storage type is used to allow a source module within a C program to access a variable declared in another source module. Static variables are only accessible within the code block that declared them, and additionally if the variable is local, rather than global, they retain their old value between subsequent calls to the code block. Register variables are stored within CPU registers where ever possible, providing the fastest possible access to their values. 15. What are register variables? What are the advantages of using register variables? Register variables is another type of storage class in C. When declared of this type it gets stored inside the CPU registers. Whenever we are going to use a variable at many places it is useful in declaring it as register because it will increase the speed of execution. 16. What is the use of typedef? Typedef is used in re declaring the variables. When ever big variable declarations are present they can be substituted using typedef. Eg: typedef unsigned long int TWO;. Whenever we want to use unsigned long int we can just use TWO. Eg: TWO var1, var2;

17. Can we specify variable field width in a scanf() format string? If possible how? Yes we can specify variable filed width within a scanf format string. An example is here we restrict string of length greater than size 20 using this statement. scanf(%20s, address). 18. Out of fgets() and gets() which function is safe to use and why? Out of fgets() and gets(), fgets() is safer because of the following reason. Fgets() reads from the file buffer until the beginning of a new line or until EOF. Whereas, in gets() it is the users work to specify length and gets() also has the danger of overrunning. 19. Difference between strdup() and strcpy()? Strcpy() is used to copy one string to another in his case we have to pass two values source and destination. Whereas. In strdup() it duplicates the string and source and destination values need not be passed. 20. What is recursion? The processes were a particular function calls itself again and again until a condition is meet is called as recursion. For example the factorial value can be calculated using recursive functions. 21. Differentiate between for loop and a while loop? We have to initialize values outside the while loop check condition and then increment inside the while loop. Whereas all three steps can be done together inside a single for loop. 22. What are different storage classes in C? C provides four storage types; extern, static, auto and register.

23. Write down the equivalent pointer expression for referring the same element a[i][j][k][l]? a[i] == *(a+i) a[i][j] == *(*(a+i)+j) a[i][j][k] == *(*(*(a+i)+j)+k) a[i][j][k][l] == *(*(*(*(a+i)+j)+k)+l) 24. What is the difference between structure and union? Both structure and union are almost similar. But the main difference is how they are stored. In structures many memory locations are grouped together. In unions a single memory location is split into many. 25. What is the advantage of using unions? Advantage of using union is that it reduces machine dependency. We no longer have to worry about the size of an int, long, float etc. 26. What are the advantages of using pointers in a program? The advantages of using pointers in programs are, they help in dynamic allocation of variables, they also help in efficient memory utilization ways, etc. 27. What is the difference between Strings and Arrays? Strings are used to handle a set of character, handling strings is a very important concept. Arrays are nothing but storing of entities of same data type in contiguous memory location. Strings are handles as a array of characters. 28. It is a repeated question 29. What is a far pointer? Where we use it? Far pointers are the normalized pointers of four bytes which are used to access the main memory of the computer ...it can access both the data segment and code segment thus by

modifying the offset u can modify refer two different addresses but refer to the same memory 30. float (*fnp[3])(int, int); 31.What is NULL pointer? Whether it is same as an uninitialized pointer? Usually a pointer is initialized to NULL. this is to tell that it is still doesn't have valid address. Uninitialized pointer can contain any value (just like any other uninitialized variable), which we call garbage. 32.What is NULL macro? What is the difference between a NULL pointer & a NULL macro? NULL is a macro which contains the value 0 (on most implementations). this is the one used to initialize a pointer to NULL. 33.What does the error Null Pointer Assignment mean and what causes this error? Null pointer assignment: This error is displayed when a value is stored to an uninitialized pointer. The program may appear to work properly. 34.What is near,far,huge pointers?How many bytes are occupied by them? near pointer: <type> near <pointer definition> ; The first version of near declares a pointer to be one word with a range of 64K. This type modifier is usually used when compiling in the medium, large, or huge memory models to force pointers to be near.

Example: char near *s; int (near *ip)[10]; When near is used with a function declaration, Turbo C++ generates function code for a near call and a near return. far pointers: Forces pointers to be far, generates function code for a far call and a far return. Syntax: <type> far <pointer definition> ; The first version of far declares a pointer to be two words with a range of 1 megabyte. This type modifier is usually used when compiling in the tiny, small, or compact models to force pointers to be far. Examples: char far *s; void * far * p; When far is used with a function declaration, Turbo C++ generates function code for a far call and a far return. huge pointer: Syntax: <type> huge <pointer-definition> ; The huge pointer is similar to the far pointer except for two additional features. 1. Its segment is normalized during pointer

arithmetic so that pointer comparisons are accurate. 2.Huge pointers can be incremented without suffering from segment wraparound. 35.How would you obtain segment and offset address from a far address of a memory location? The segment and offset address can be calculated by means of using the function FP_SEG().The parameter to the function is fp which is the file pointer.It is given as FP_SEG(fp).This function returns the segment and offset address of the given memory location. 36.Are the expressions arr and &arr same for an array of integers? The __expression arr and &arr are same for an array of integers.

37.Does mentioning the array name gives the base address in all the contexts? No, not in all contexts. Following is the list of exceptions. An expression of type array of type is converted to type pointer to type unless: * it is the operand of the sizeof operator, or * it is the operand of the address-of (&) operator, or * it is a string literal used to initialize an array. 38. Explain one method to process an entire string as one unit? Strlen()-This function counts the number of charcters present in a string. Ex:

main() { char arr*+=London; int len; len=strlen(arr); printf(string = %s length=%d,arr,len); } Output: String= London length=6 39. What is the similarity between a structure, union and enumeration? The similarity between a structure, union and enumeration is all the three are defined by the user. 40. Can a structure contain a pointer to itself? Yes, structure can contain a pointer to itself. typedef struct node { char *item; struct node *next; } *NODEPTR; 41.How can we check whether the contents of two structure variables are same or not? Two variables of the same structure type can be compared in same way as ordinary variables. If person1 & person2 belongs to same structure the following operations are valid. Operation Person1=person2 Person1==person2 Meaning Assign person2 to person1 Compare all members of person1 &person2 & return 1 if

Person1!=person2

they are equal, zero otherwise. Return 1 if all the member are not equal, zero otherwise.

42. How are structure passing and returning implemented by compiler? When structures are passed as arguments to functions, the entire structure is typically pushed on the stack, using as many words as are required. 43. How can we read/write structures from/to data files? We ca n read/write structures from/to data files by using fscanf()&fprintf(). 44. What is the difference between enumeration and a set of preprocessor #defines? #define have a global scope whereas the scope of enum can either be global (if declared outside all function) or local (if declared inside a function). 45. What do the c and v in argc and argv stand for? Argc-argument count Argv-argument vector 46. Are the variables argc and argv are local to main? Yes, the variables argc and argv are local to main. 47. 48. It is the command interpreters job to do the expansion. 49. 50. What are bitfields?What is the use of bitfields in structure declaration? A bit field is an element of a structure that is defined in terms of bits.Using a special type of struct definition, you can

declare a structure element that can range from 1 to 16 bits in length. For example, this struct struct bit_field { int bit_1 : 1; int bits_2_to_5 : 4; int bit_6 : 1; int bits_7_to_16 : 10; } bit_var; 51. To which numbering system can the binary number 1101100100111100 be easily converted to? Hexadecimal Numbering System. 52. Which bitwise operator is suitable for checking whether a particular bit is on or off? Bitwise AND Operator. 53. Which bitwise operator is suitable for turning off a particular bit in a number? Bitwise AND Operator. 54. Which bitwise operator is suitable for putting on a particular bit in a number? Bitwise OR Operator. 55. Which bitwise operator is suitable for checking whether a particular bit is on or off? Bitwise AND Operator. 56.Which is equivalent to multiplying by 2:Left shifting a number by 1 or left shifting an unsigned int or char by 1? Left shifting a number by 1 is equivalent to multiplying by 2. It is always safe to use unsigned integer operands for bitwise operations, so the second statement will hold good.

57. Write a program to compare two strings without using the strcmp() function? 58.Write a program to concatenate two string? Program: #include<stdio.h> void main() { char source*+=folks!; char target*30+=Hello; strcat(target,source); printf(\nsource string=%s,source); printf(\ntarget string=%s,target); } 59.Write a program to interchange two variables without using the third one? Program: #include<stdio.h> void main(){ int a,b; printf("ENTER THE VALUE OF A : "); scanf("%d",&a); printf("ENTER THE VALUE OF B : "); scanf("%d",&b); if (a>b) {a=a-b; b=a+b; a=b-a; } else {b=b-a;

a=b+a; b=a-b;} printf ("A = %d \nB = %d",a,b); } 60.Write a program for String reversal & palindrome check? Program: #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str1[20],str2[20]; clrscr(); printf("\nEnter the string: "); scanf("%s",&str1); strcpy(str2,str1); strrev(str1); 61. Write a program to find the Factorial of a number #include <stdio.h> #define VALUE 6 int i,j; void main() { j=1; for (i=1; i<=VALUE; i++) j=j*i; printf("The factorial of %d is %d\n",VALUE,j); } 62.Write a program to generate the Fibinocci Series

#include <stdio.h> main() { int fib[24]; int i; fib[0] = 0; fib[1] = 1; for(i = 2; i < 24; i++) fib[i] = fib[i-1] + fib[i-2]; for (i = 0; i < 24; i++) printf("%3d %6d\n", i, fib[i]); } 63.Write a program which employs Recursion Program to display first four multiples of a number #include<stdio.h> #include<conio.h> Void multi(); Void main() { Int I; Clrscr(); Multi(10); Getch(); } Void multi(int n) { If(n<10000) { Multi(n*10); } Printf(\n%d,n);

} Output: 10000 1000 100 10 64.Write a program which uses Command Line Arguments Weight Conversion with Command Line Argument #include <stdio.h> void print_converted(int pounds) /* Convert U.S. Weight to Imperial and International Units. Print the results */ { int stones = pounds / 14; int uklbs = pounds % 14; float kilos_per_pound = 0.45359; float kilos = pounds * kilos_per_pound; printf(" %3d %2d %2d %6.2f\n", pounds, stones, uklbs, kilos); } main(int argc,char *argv[]) { int pounds; if(argc != 2) { printf("Usage: convert weight_in_pounds\n"); exit(1); } sscanf(argv[1], "%d", &pounds); /* Convert String to int */ printf(" US lbs UK st. lbs INT Kg\n"); print_converted(pounds);

} 65.Write a program which uses functions like strcmp(), strcpy()? etc #include <stdio.h> /* stdin, printf, and fgets */ #include <string.h> /* for all the new-fangled string functions */ /* this function is designed to remove the newline from the end of a string entered using fgets. Note that since we make this into its own function, we could easily choose a better technique for removing the newline. Aren't functions great? */ void strip_newline( char *str, int size ) { int i; /* remove the null terminator */ for ( i = 0; i < size; ++i ) { if ( str[i] == '\n' ) { str[i] = '\0'; /* we're done, so just exit the function by returning */ return; } } /* if we get all the way to here, there must not have been a newline! */

} int main() { char name[50]; char lastname[50]; char fullname[100]; /* Big enough to hold both name and lastname */ printf( "Please enter your name: " ); fgets( name, 50, stdin ); /* see definition above */ strip_newline( name, 50 ); /* strcmp returns zero when the two strings are equal */ if ( strcmp ( name, "Alex" ) == 0 ) { printf( "That's my name too.\n" ); } else { printf( "That's not my name.\n" ); } // Find the length of your name printf( "Your name is %d letters long", strlen ( name ) ); printf( "Enter your last name: " ); fgets( lastname, 50, stdin ); strip_newline( lastname, 50 ); fullname[0] = '\0'; /* strcat will look for the \0 and add the second string starting at that location */ strcat( fullname, name ); /* Copy name into full name */

strcat( fullname, " " ); /* Separate the names by a space */ strcat( fullname, lastname ); /* Copy lastname onto the end of fullname */ printf( "Your full name is %s\n",fullname ); getchar(); return 0; }

66.What are the advantages of using typedef in a program? A good programming practice is using typedef while instantiating template classes. Then throughout the program, one can use the typedef name. There are two advantages: typedef's are very useful when "templates of templates" come into usage. For example, when instantiating an STL vector of int's, you could use: typedef vector&ltint, allocator&ltint> > INTVECTOR ; If the template definition changes, simply change the typedef definition. For example, currently the definition of template class vector requires a second parameter. typedef vector&ltint, allocator&ltint> > INTVECTOR ; INTVECTOR vi1 ;

67.How would you dynamically allocate a one-dimensional and two-dimensional array of integers? int **arrayPtr; int numRows, numCols; printf("Enter values for numRows and numCols\n"); scanf("%d",&numRows);

scanf("%d",&numCols); /* Create space for first array (array of pointers to each row). */ arrayPtr = (int **) malloc(numRows*sizeof(int)); /* Loop through first array and create space for according to number of columns.*/ for(rowIndex=0;rowIndex < numRows;rowIndex++) arrayPtr[rowIndex] = malloc(numCols*sizeof(int)); The easiest way to create a dynamically allocated array is to first dynamically allocate an array of pointers, of length equal to the number of rows desired, and then have each entry in that array point to a dynamically allocated array of length equal to the number of columns. The following example allocates a dynamic array of characters with eight rows and 5 columns. main() { char **myArray; // eek, char ** because myArray is a pointer to a // pointer to a character (an array of arrays...) myArray = new char * [8]; // allocate the rows for (int row = 0; row < 8; row++) // now allocate the columns myArray[i] = new char [5]; } 68.How can you increase the size of a dynamically allocated array? Realloc() function is used to resize the memory block,which is already allocated.

Syntax: ptr_var=realloc(ptr_var,new_size); 69.How can you increase the size of a statically allocated array? Required amount of memory is allocated to program elements at start of the program. memory value is fixed and identified by compiler at compile time. So statically allocated memory size cannot be resized. 70.When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically? If you have a pointer to a malloc'd section of memory and you realloc it, the pointer still points to the right addrss, but the actual address *may* change. 71.Which function should be used to free the memory allocated by calloc()? The Free() function Syntax: free(ptr_var); 72.How much maximum can you allocate in a single call to malloc()? Depending upon the amount of free memory in the ram,the size is allocated to malloc in single call. To check whether requested memory is available the following program is used.. Int ptr*; Prt=(int*)malloc(5*sizeof(int)); If (prt==NULL) { Printf(required memory not available); Getch();exit(0);

} 73.Can you dynamically allocate arrays in expanded memory? ====== 74.What is object file? How can you access object file? The compiler compiles the error free source code and coverts them into byte code format and this file is called the object file. Thus the text editor produces .c source files, which go to the compiler, which produces .obj object files, which go to the linker, which produces .exe executable file 75.Which header file should you include if you are to develop a function which can accept variable number of arguments? Stat.h 76.Can you write a function similar to printf()? The library function sprintf() is similar to printf() only the formatted output is written to a memory area rather than directly to standard output. It is particularly useful when it is necessary to construct formatted strings in memory for subsequent transmission over a communications channel or to a special device main() { char buf[128]; double x = 1.23456; char *spos = buf; int i = 0; sprintf(buf,"x = %7.5lf",x); while(i<10) puts(spos+i++);

} OUTPUT: x = 1.23456 = 1.23456 = 1.23456 1.23456 1.23456 .23456 23456 3456 456 56 77.How can a called function determine the number of arguments that have been passed to it? Depending upon the number of arguments passed the called function will be selected accordingly. Ex: a)void volume(int length,int breath,int height) b)void volume(int length,int breath) When a=volume(2,3) then [b] will be called. If a=volume(3,6,7) then [a] will be called. 78.Can there be at least some solution to determine the number of arguments passed to a variable argument list function? 79.How do you declare the following: o An array of three pointers to chars char *name[] = { "Dave","Bert","Alf" }; o An array of three char pointers o A pointer to array of three chars

A pointer to function which receives an int pointer and returns a float pointer A pointer to a function which receives nothing and returns nothing

80.What do the functions atoi(), itoa() and gcvt() do? gcvtConvert floating point value to string * itoaConvert integer to string atoiConvert string to integer 81.Does there exist any other function which can be used to convert an integer or a float to a string? ecvtConvert floating point value to string * fcvtConvert floating point value to string 82.How would you use qsort() function to sort an array of structures? qsort will sort an array of elements. This is a wild function that uses a pointer to another function that performs the required comparisons. Library : stdlib.h Prototype : void qsort(void *base, size_t num, size_t size, int (*comp_func)(const void *, const void *)) 83.How would you use qsort() function to sort the name stored in an array of pointers to string? void *qsort(const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); void Person_dbase::list(Listtype type) {

switch (type) { case list_by_name: qsort(pp, n, sizeof(Person), (pif2vp)cmpname); break; case list_by_birthday: qsort(pp, n, sizeof(Person), (pif2vp)cmpdate); break; } // list the sorted Person-database } 84.How would you use bsearch() function to search a name stored in array of pointers to string? void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); 85.How would you use the functions sin(), pow(), sqrt()? #include <math.h> sin(): double sin(double x); sin()- gives the trignometrical sin value of x which is in radian. pow(): double sqrt(double x); sqrt() returns the non-negative square root of x. The value of x must not be negative. sqrt(): float powf(float x, float y);

pow() returns x^y. If x is 0.0, y must be positive. If x is negative, y must be an integer. 86.How would you use the functions memcpy(), memset(), memmove()? Declaration: memcpy(): void *memcpy(void *str1, const void *str2, size_t n); Copies n characters from str2 to str1. If str1 and str2 overlap the behavior is undefined. Declaration: memset(): void *memset(void *str, int c, size_t n); Copies the character c (an unsigned char) to the first n characters of the string pointed to by the argument str. Declaration: memmove(): void *memmove(void *str1, const void *str2, size_t n); Copies n characters from str2 to str1. If str1 and str2 overlap the information is first completely read from str1 and then written to str2 so that the characters are copied correctly. 87.How would you use the functions fseek(), fread(), fwrite() and ftell()? Fseek(): int fseek(FILE *stream, long offset, int mode); The function sets the file-position indicator for the stream stream (as specified by offset and mode), clears the end-of-file indicator for the stream, and returns zero if successful. Fread(): size_t fread(void *ptr, size_t size, size_t nelem, FILE *stream);

The function reads characters from the input stream stream and stores them in successive elements of the array whose first element has the address (char *)ptr until the function stores size*nelem characters or sets the end-of-file or error indicator. It returns n/size, where n is the number of characters it read. If n is not a multiple of size, the value stored in the last element is indeterminate. If the function sets the error indicator, the fileposition indicator is indeterminate. Fwrite(): size_t fwrite(const void *ptr, size_t size, size_t nelem, FILE *stream); The function writes characters to the output stream stream, accessing values from successive elements of the array whose first element has the address (char *)ptr until the function writes size*nelem characters or sets the error indicator. It returns n/size, where n is the number of characters it wrote. If the function sets the error indicator, the file-position indicator is indeterminate. Ftell(): long ftell(FILE *stream); The function returns an encoded form of the file-position indicator for the stream stream or stores a positive value in errno and returns the value -1. For a binary file, a successful return value gives the number of bytes from the beginning of the file. For a text file, target environments can vary on the representation and range of encoded file-position indicator values. 88.How would you obtain the current time and difference between two times? BY USING TIMERELATED FUNCTIONS Time() - Gets current system time as long integer Difftime - Computes the difference between two times

89.How would you use the functions randomize() and random()? int randno = random(n); It then returns a random whole number in the range 0 to n-1 BY using randomize() - Initializes random number generation with a random value based on time. 90.How would you implement a substr() function that extracts a sub string from a given string? substr(s,p)-- return substring of s starting at position p 91.What is the difference between the functions rand(), random(), srand() and randomize()? srand ... Sets a new random seed for rand rand ... returns a pseudo-random number (using the seed from srand call) random and srandom are pretty mucht the same as rand and srand but the have a better alorithm -> the numbers are more random randomize is probably a Borland specific function 92.What is the difference between the functions memmove() and memcpy()? memmove() Copies n characters from str2 to str1. If str1 and str2 overlap the behavior is undefined memcpy() Copies n characters from str2 to str1. If str1 and str2 overlap the information is first completely read from str1

and then written to str2 so that the characters are copied correctly 93.How do you print a string on the printer? BY USING: stdprn()-[standard printer] function. 94.Can you use the function fprintf() to display the output on the screen? yes it is possible as

Potrebbero piacerti anche