Thursday, November 20, 2008

scan strings from keyboard in case of array of pointers to string

What would be the output of following program?
struct syntax
{
int i ;
float g ;
char c ;
}
main( )
{
printf ( "I won't give you any error" ) ;
}
Ans: The above program would get compiled successfully and on execution it would print the message given in printf(). What strikes in the above code snippet is the structure syntax which is declared but not terminated with the statement terminator, the semicolon. The compiler would not give any error message for it, as it assumes that main( ) function have a return type of struct syntax and hence would successfully compile and execute the program.


78. Suppose we have a floating-point number with higher precision say 12.126487687 and we wish it to be printed with only precision up to two decimal places. How can I do this?

Ans. This can achieved through the use of suppression char '*' in the format string of printf( ) which is shown in the following program.
main( )
{
int p = 2 ;
float n = 12.126487687 ;
printf ( "%.*f",p, n ) ;



Why is it not possible to scan strings from keyboard in case of array of pointers to string?

Ans: When an array is declared, dimension of array should be specified so that compiler can allocate memory for the array. When array of pointers to strings is declared its elements would contain garbage addresses. These addresses would be passed to scanf( ). So strings can be received but they would get stored at unkown locations. This is unsafe.

No comments:

Blog List