C Interview Questions and Answers Part 1

10/18/2010 No Comment
Question:What will be the output of the following code?
void main ()
{ int i = 0 , a[3] ;
a[i] = i++;
printf (“%d",a[i]) ;
}

Answer: The output for the above code would be a garbage value. In the statement a[i] = i++; the value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value.

Question:Why doesn't the following code give the desired result?
Answer: int x = 3000, y = 2000 ;
long int z = x * y ;
Ans: Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below:
long int z = ( long int ) x * y ;
Note that ( long int )( x * y ) would not give the desired effect.

Question: Why doesn't the following statement work?
char str[ ] = "Hello" ;
strcat ( str, '!' ) ;
Answer: The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below:
strcat ( str, "!" ) ;

Question:How do I know how many elements an array can hold?
Answer: The amount of memory an array can consume depends on the data type of an array. In DOS environment, the amount of memory an array can consume depends on the current memory model (i.e. Tiny, Small, Large, Huge, etc.). In general an array cannot consume more than 64 kb. Consider following program, which shows the maximum number of elements an array of type int, float and char can have in case of Small memory model.
main( )
{
int i[32767] ;
float f[16383] ;
char s[65535] ;
}

Question:How do I write code that reads data at memory location specified by segment and offset?
Answer: Use peekb( ) function. This function returns byte(s) read from specific segment and offset locations in memory. The following program illustrates use of this function. In this program from VDU memory we have read characters and its attributes of the first row. The information stored in file is then further read and displayed using peek( ) function.
#include
main( )
{
char far *scr = 0xB8000000 ;
FILE *fp ;
int offset ;
char ch ;
if ( ( fp = fopen ( "scr.dat", "wb" ) ) == NULL )
{
printf ( "\nUnable to open file" ) ;
exit( ) ;
}
// reads and writes to file
for ( offset = 0 ; offset < fp =" fopen" offset =" 0">

Related Posts


No comments :

 

Aired | The content is copyrighted and may not be reproduced on other websites. | Copyright © 2009-2016 | All Rights Reserved 2016

Contact Us | About Us | Privacy Policy and Disclaimer