C Interview Questions Part 6

Q:The sizeof( ) function doesn’t return the size of the block of memory pointed to by a pointer. Why?
A:The sizeof( ) operator does not know that malloc( ) has been used to allocate a pointer. sizeof( ) gives us the size of pointer itself. There is no handy way to find out the size of a block allocated by malloc( ).



Q: What is FP_SEG And FP_OFF…
A:Sometimes while working with far pointers we need to break a far address into its segment and offset. In such situations we can use FP_SEG and FP_OFF macros. Following program illustrates the use of these two macros.
#include
main( )
{
unsigned s, o ;
char far *ptr = "Hello!" ;
s = FP_SEG ( ptr ) ;
o = FP_OFF ( ptr ) ;
printf ( "\n%u %u", s, o ) ;
}

Q:How do I write a program to convert a string containing number in a hexadecimal form to its equivalent decimal?
A: The following program demonstrates this:
main( )
{
char str[] = "0AB" ;
int h, hex, i, n ;
n = 0 ; h = 1 ;
for ( i = 0 ; h == 1 ; i++ )
{
if ( str[i] >= '0' && str[i] <= '9' )
hex = str[i] - '0' ;
else
{
if ( str[i] >= 'a' && str[i] <= 'f' )
hex = str[i] - 'a' + 10 ;
else
if ( str[i] >= 'A' && str[i] <= 'F' )
hex = str[i] - 'A' + 10 ;
else
h = 0 ;
}
if ( h == 1 )
n = 16 * n + hex ;
}
printf ( "\nThe decimal equivalent of %s is %d",
str, n ) ;
}
The output of this program would be the decimal equivalent of 0AB is 171.

Q:How do I write code that reads the segment register settings?
A: We can use segread( ) function to read segment register settings. There are four segment registers—code segment, data segment, stack segment and extra segment. Sometimes when we use DOS and BIOS services in a program we need to know the segment register's value. In such a situation we can use segread( ) function. The following program illustrates the use of this function.
#include
main( )
{
struct SREGS s ;
segread ( &s ) ;
printf ( "\nCS: %X DS: %X SS: %X ES: %X",s.cs,
s.ds, s.ss, s.es ) ;
}