C Interview Questions Part 15

Q:How do I write code to get the current drive as well as set the current drive?
A: The function getdisk( ) returns the drive number of current drive. The drive number 0 indicates 'A' as the current drive, 1 as 'B' and so on. The Setdisk( ) function sets the current drive. This function takes one argument which is an integer indicating the drive to be set. Following program demonstrates use of both the functions.

#include
main( )
{
int dno, maxdr ;
dno = getdisk( ) ;
printf ( "\nThe current drive is: %c\n", 65 + dno
) ;
maxdr = setdisk ( 3 ) ;
dno = getdisk( ) ;
printf ( "\nNow the current drive is: %c\n", 65 +
dno ) ;
}
Q: How do I compare character data stored at two different memory locations?
A: Sometimes in a program we require to compare memory ranges containing strings. In such a situation we can use functions like memcmp( ) or memicmp( ). The basic difference between two functions is that memcmp( ) does a case-sensitive comparison whereas memicmp( ) ignores case of characters. Following program illustrates the use of both the functions.

#include
main( )
{
char *arr1 = "Kicit" ;
char *arr2 = "kicitNagpur" ;
int c ;
c = memcmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 )
printf ( "\nStrings arr1 and arr2 compared using memcmp are identical" ) ;
else
printf ( "\nStrings arr1 and arr2 compared using memcmp are not identical") ;
c = memicmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 )
printf ( "\nStrings arr1 and arr2 compared using memicmp are identical" );
else
printf ( "\nStrings arr1 and arr2 compared using memicmp are not identical" ) ;
}

Fixed-size objects are more appropriate as compared to variable size data objects. Using variable-size data objects saves very little space. Variable size data objects usually have some overhead. Manipulation of fixed-size data objects is usually faster and easier. Use fixed size when maximum size is clearly bounded and close to average. And use variable-size data objects when a few of the data items are bigger than the average size. For example,

char *num[10] = { "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ;

Instead of using the above, use
char num[10][6] = { "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ;

The first form uses variable-size data objects. It allocates 10 pointers, which are pointing to 10 string constants of variable size. Assuming each pointer is of 4 bytes, it requires 90 bytes. On the other hand, the second form uses fixed size data objects. It allocates 10 arrays of 6 characters each. It requires only 60 bytes of space. So, the variable-size in this case does not offer any advantage over fixed size.