Showing posts with label C Interview Questions. Show all posts
Showing posts with label C Interview Questions. Show all posts

Interview questions on Bitwise Operators

1)Which bit wise operator is suitable for turning off a particular bit in a number?

2)what will be printed out when the following code is executed:

main()
{
printf("%x",-1<<4);
}

3)Which one is equivalent to multiplying by 2?

* Left shifting a number by 1
* Left shifting an unsigned int or char by 1?

4)Write a function which gets the n bits from an unsigned integer x, starting from position p .(the right most digit is at position 0)

5)Write a function using bitwise opetators to check whether an integer is a power of 2 or not?

6)Write a Program that swaps the contents of two variables without
using any other variable,using bitwise operators?

7) Which bit wise operator is suitable for checking whether a particular bit is on or off?

8) Which bit wise operator is suitable for putting on a particular bit in a number?

9) Which bit wise operator is suitable for checking whether a particular bit is on or off?

10)Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y,leaving the other bits changed.

11)Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted leaving other unchanged.

Please post your answers in the comments section.Answers Shall soon be put.

Basic C Questions to test ur expertise -11

1.
Sample Code
#include
int main(void) {
{int i=10; goto lbl;}
{int i=20; {int i=30; lbl:;}
printf("%i", ++i);}
}


Refer to the above sample code. What does this program print?
1 10
2 11
3 21
4 31
5 An undefinedvalue


2.
short testarray[4][3] = { {1}, {2, 3}, {4, 5, 6} };
printf( "%d\n", sizeof( testarray ) );

Assuming a short is two bytes long, what will be printed by the above code?
1 It will not compile because not enough initializers are given.
2 6
3 7
4 12
5 24


3.
Which of the following choices most accurately describes variable DEFINITION (as opposed to declaration)?

1 The assignment of properties and storage space to a variable
2 The identification of a variable that resides elsewhere in the program
3 The assignment of storage space to a variable
4 The assignment of properties to a variable
5 The assignment of storage space to a variable whose
properties have been specified external to the current file scope


4.
How do you include a system header file called
sysheader.h in a C source file?

1 #includefile
2 #include sysheader.h
3 #incl "sysheader.h"
4 #include
5 #incl


5.
Sample Code
f = fopen( fileName, "r" );

From the sample above, which one of the following statements will set the file position for the file f to cause the next byte read from the file to be the last byte?

1 f = feof( f ) - 1;
2 fsetpos( f, EOF - 1 );
3 fseek( f, -1, SEEK_SET );
4 fseek( f, -1, EOF );
5 fseek( f, -1, SEEK_END );


6.
/* Initialize an array with zero values. */
void bzero (void * b, size_t len) {
char *buf = b;
int i;

for (i = 0; i <= len; i++) *(buf + i) = 0; } The function bzero(), defined above, contains a common programming error. Which one of the following correctly describes it? 1 The loop writes beyond the end of buf. 2 buf refers to an array and should be indexed as one; the pointer notation applied by the loop causes the wrong address to be dereferenced. 3 It is not permitted to declare objects of type size_t; this type is reserved for exclusive usage by the standard library's internal routines. 4 A generic pointer cannot be cast to a pointer of a more specific type. 5 The comparison between int i and size_t len is not permitted by Standard C.


7.
Sample Code
long factorial (long x)
{
return x * factorial(x - 1);
}

What will the function above return if called with x equal to 5?

1 0
2 15
3 120
4 The program will not compile.
5 The function will never return.


8.
Which one of the following describes a C character string?

1 A sequence of char objects in EBCDIC format
2 A sequence of printable ASCII characters
3 Any pointer to type char
4 An array of bytes terminated by NUL
5 A sequence of char objects in ASCII format


9.
#include %lt;stdlib.h>
int f(TYPE x) {
/*Allocates an array of two integers; returns 0
if the allocation succeeded, 1 otherwise.
Returns the allocated array in x.
*/
int *ret = (int*)malloc(sizeof(int[2]));
return ret ? *x=ret, 0 : 1;
}
Referring to the sample code above, how should TYPE be declared?

1 typedef int**TYPE;
2 typedef int*TYPE;
3 typedef int[]TYPE;
4 typedef &(int*)TYPE;
5 typedef int[]*TYPE;


10.
Which one of the following is a valid variable name?

1 Account_Number
2 Account Number
3 "Account Number"
4 Account^Number
5 Account-Number


11.
/* fp points to an open stream.
* Process a full stream of binary data. */
unsigned long process_binary_data(FILE *fp) {
char ch;
unsigned long count = 0UL;

assert(fp != NULL);
while ((ch = fgetc(fp)) != EOF) {
process_byte(ch);
count++;
}

return count;
}

The function process_binary_data(), defined above, may fail to process the entire stream under exceptional conditions. Which one of the following explains this error?

1 The disparity between the type of ch and the type of EOF causes the loop to execute forever.
2 The loop may fail to process the entire stream underlying fp because it does not check for errors.
3 It is incorrect to use the assignment operator in a loop condition. The programmer probably meant to use the equality operator.
4 The function body contains incorrectly nested parentheses.
5 count fails to contain the number of bytes actually processed.


12.
int x = 3;

if( x == 2 ); x = 0;
if( x == 3 ) x++;
else x += 2;
What value will x contain when the sample code above is executed?

1 1
2 2
3 3
4 4
5 5


13.
int x[] = {1, 2, 3, 4, 5};
int *ptr, **ptr2;

ptr = x;
ptr2 = &ptr;
Referring to the sample code above, how do you update x[2] to 10 using ptr2?

1 (**ptr2 + 2) = 10;
2 **(ptr2 + 2) = 10;
3 *(*ptr2 + 2) = 10;
4 *(&ptr2 + 2) = 10;
5 **(*ptr2 + 2) = 10;


14.
Which one of the following declarations ensures that ptr CANNOT be used to modify the string to which it points (although ptr itself may be changed to point to another string)?
1 static char *ptr = "Hello";
2 const char *ptr = "Hello";
3 char *ptr = const "Hello";
4 char * static ptr = "Hello";
5 char * const ptr = "Hello";


15.
int a [25];
int * p = a + 3;

Which one of the following is functionally equivalent to the code fragment above?

1 int a [25];
int * p = &a[3];

2 int a [25];
int * p = &(a + 3);

3 int a [25];
int * p = &a[2];

4 int a [25];
int * p = (&a)[3];

5 int a [25];
int * p = a[3];


16.
Which one of the following code fragments causes k to contain the value 16 at some point?

1 int j = 14;
int k = 1;
k += j+;

2 int k;
**((int **) &k) = 16;

3 int j;
int k = 4;
j = k <<>> 11;
k += j;

4 int j, k;
j = 2 << k =" j" j =" 256;" k =" 14;" k =" j">


17.
Sample Code

#define X(t,m) (size_t)((char*)&((t*)0)->m-(char*)(t*)0)

Consider the poorly named macro X(), defined above. Of which one of the following Standard C macros could X() be an implementation?
1 va_start()
2 putchar()
3 va_arg()
4 offsetof()
5 feof_unlocked()


18.
For which one of the following reasons did the writers of MS-DOS C compilers augment C by adding the reserved words __near, __far, and __huge?

1 They are reserved for usage by compiler writers and have no relevance to other programmers, hence the leading pair of underscores.
2 They indicate that the compiler should place objects in the data segment, on the stack, and on the heap, respectively.
3 They are specific to x86 architecture, and allow the programmer to override the default memory model for specific objects.
4 They allow the compiler to perform additional code optimizations on pointer values.
5 They indicate that an object should be placed near the lowest address, near the highest address, and that an object requires multiple pages, respectively.


19.
Sample Code
extern void *ptr1;
extern void *ptr2;

int compare( int n )
{
return ????;
}

What should replace the ???? in the code above to compare the first n bytes of the memory pointed to by ptr1 and ptr2 and return a non-zero value if they are equal?

1 memcmp( ptr1, ptr2, n )
2 !memcmp( ptr1, ptr2, n )
3 !strncmp( ptr1, ptr2, n )
4 memncmp( ptr1, ptr2, n )
5 strncmp( ptr1, ptr2, n )

20.
Sample Code
void memset (void * buf, int c, size_t len) ??< unsigned char * b; register int i; assert(buf); debug("assert(buf) => TRUE??/n");
b = buf;
for (i = 0; i <>
??>

Consider the function memset(), defined above. Which one of the following is a completely true statement about the code shown above?

1 Some accesses performed on b are out-of-bounds.
2 Providing that debug() is declared and correctly used, the code compiles correctly under a Standard C compiler.
3 The three-character sequences starting with ?? were inserted by Microsoft Word.
4 The source code file containing memset() has probably become corrupted. This code clearly does not compile.
5 Assuming that debug() prints its string argument, the strings will run together on the same line.


21.

Which one of the following is the result type of the sizeof operator?

1 unsigned char
2 int
3 char
4 unsigned int
5 size_t


22.
Which one of the following best describes the Standard C convention regarding variables with names that start with an underscore (_)?
1 They are reserved for usage by standards committees, system implementers, and compiler engineers.
2 They are deprecated by Standard C and are permitted only for backward compatibility with older C libraries.
3 Applications programmers are encouraged to employ them in their own code in order to mark certain symbols for internal usage.
4 They are case-insensitive.
5 They are generally treated differently by preprocessors and compilers from other identifiers.


23.
Sample Code
int i,j;
int ctr = 0;
int myArray[2][3];

for (i=0; i<; i++) for (j=0; j<2;>


24.
Sample Code
int i = 4;

switch (i)
{
default:
;
case 3:
i += 5;

if ( i == 8)
{
i++;
if (i == 9) break;

i *= 2;
}

i -= 4;

break;

case 8:
i += 5;
break;
}

printf("i = %d\n", i);

What will the output of the sample code above be?

1 i = 5
2 i = 8
3 i = 9
4 i = 10
5 i = 18


25.
Which one of the following functions returns the string representation from a pointer to a time_t value?
1 localtime
2 gmtime
3 ctime
4 strtime
5 asctime


26.
Which one of the following is a true statement about an lvalue?

1 An lvalue is the result of an arithmetic operation involving quantities of type long int.
2 All lvalues can be used on the right side of an assignment statement.
3 An lvalue is, by definition, the value appearing on the rightmost side of an assignment
statement.
4 By definition, an lvalue is the storage space indirectly referenced by a pointer.
5 An lvalue is any quantity capable of appearing on the left side of a shift operator.


27.
Which one of the following is a true statement about non-generic (void *) pointers?

1 For efficiency, pointer values are always stored in machine registers.
2 A pointer to one type may not be cast to a pointer to any other type.
3 Similarly typed pointers may be subtracted from each other.
4 They are always 32-bit values.
5 Similarly typed pointers may be added to each other.


28.
Which one of the following will read a character from the keyboard and will store it in the variable c?

1 c = getchar();
2 c = getchar( stdin );
3 getchar( &c )
4 getc( &amp;c );
5 c = getc();


29.
Which one of the following is NOT a valid statement?

1 ++d+++e++;
2 f*=g+=h=5;
3 l-->>m<<--n; 4 int a(int a),b=0,c=a((c=b,++b)); 5 i->j<-k;


30.
int factorial (int x) {
extern jmp_buf jb;
int fact, chk;
if (!x) return 1;
fact = x * (chk = factorial(x - 1));
if (chk > fact) longjmp(jb, -1);
return fact;
}

int check_for_overflow (int x) {
extern jmp_buf jb;
if (setjmp(jb)) {
printf("discovered overflow in factorial(%d)\n", x);
return 0;
}
if (x < x =" 0;">
return factorial(x);
}

There is an error in check_for_overflow that may occasionally result in unexpected values in var jb. Which one of the following describes this error?

1 longjmp() cannot safely be used to escape from a recursive call chain.
2 The argument to check_for_overflow() should be qualified with volatile to ensure correct
error reporting.
3 setjmp() and longjmp() must be invoked within the same stack frame. The result of longjmp()
in this case is undefined.
4 The calls to setjmp() and longjmp() operate on different jump buffers, and therefore may
have an undefined effect.
5 The factorial of zero (0) is incorrectly handled by factorial().

31.
The mostly redundant reserved word auto signifies that the compiler should allocate
storage for a variable ___________.

Which one of the following correctly completes the statement above?

1 Only on the stack
2 Only in a register
3 Only until the end of the block
4 Only in the data segment
5 Only on the heap


32.
Which of the following correctly enumerate predefined streams?

1 stddev, stdprn, and stdmon
2 stdin, stdout, and stderr
3 stdin, stdout, and stdterm
4 stdio and stderr
5 stdin, stdlib, and stderr


33.
Which one of the following Standard C functions can be used to sort a string array?
1 qsort
2 sort
3 quicksort
4 asort
5 There is no Standard C function for such a sort.


34.
An expression consisting solely of literals can appear anywhere that literals of the same type can appear.
Which one of the following correctly assesses the statement above?
1 The statement is true.
2 The statement is false. A constant expression may contain side effects that prevent it from
being evaluated at compile time. Since it cannot be universally permitted, it is universally
prohibited.
3 The statement is false. While a constant expression could logically appear wherever a
literal could appear, the Standard C committee chose to allow constant expressions only in
runtime contexts.
4 The statement is false. A constant expression cannot appear as the operand of sizeof or in
the size definition of an array.
5 The statement is false. To simplify the design of the compiler, C compiler implementers are
not obliged to evaluate constant expressions at compile time.


35.
/* sys/cdef.h */
#if defined(__STDC__) || defined(__cplusplus)
#define __P(protos) protos
#else
#define __P(protos) ()
#endif

/* stdio.h */
#include
div_t div __P((int, int));

The code above comes from header files for the FreeBSD implementation of the C library. What is the primary purpose of the __P() macro?

1 The __P() macro provides backward compatibility for K&R C compilers, which do not recognize
Standard C prototypes.
2 The __P() macro has no function, and merely obfuscates library function declarations.
It should be removed from further releases of the C library.
3 The __P() macro provides forward compatibility for C++ compilers, which do not recognize
Standard C prototypes.
4 Identifiers that begin with two underscores are reserved for C library implementations.
It is impossible to determine the purpose of the macro from the context given.
5 The __P() macro serves primarily to differentiate library functions from
application-specific functions.


36.
Sample Code
int aFunction(int y)
{
int x = 3 * y;

return x;
}
In the sample code above, with what scope is the variable x implicitly declared?

1 extern
2 static
3 auto
4 volatile
5 register


37.
Which one of the following statements regarding macros is INCORRECT?
1 Macro definitions can contain expressions.
2 Macro definitions cannot be altered at runtime.
3 Macros can have parameters.
4 Macros are evaluated in the preprocessor.
5 Macros are evaluated at runtime.


38.
Sample Code
void listFile( FILE *f )
{
int c;
while( c = fgetc( f ) != EOF )
{
printf( "%d", c );
}
printf( "\n" );
}

What will be printed when the function above is called with a pointer to an open file that contains the three characters abc?

1 111
2 000
3 656667
4 abc
5 The characters ab followed by an infinite number of c's


39.
Which one of the following will turn off buffering for stdout?

1 setbuf( stdout, NULL );
2 setbuf( stdout, FALSE );
3 setvbuf( stdout, NULL );
4 setbuf( stdout, _IONBF );
5 setvbuf( stdout, _IONBF );

40.
Sample Code
char buf[ 50 ] = "Hello World";
char *ptr = buf + 5;

From the sample above, what is the proper way to copy 20 bytes from the location pointed to by ptr to the beginning of buf?
1 memcpy( buf, ptr, 20 );
2 It cannot be done because the source and destination overlap.
3 strncpy( buf, ptr, 20 );
4 That may cause an illegal memory access because it will read memory past the end of the string.
5 memmove( buf, ptr, 20 );


41.
Which one of the following will declare a pointer to an integer at address 0x200 in memory?

1 int *x = &0x200;
2 int *x = *0x200;
3 int *x( &0x200 );
4 int *x;
*x = 0x200;
5 int *x = 0x200;


42.
int *x;
x = (int *) 15;

Is the above code legal?

1 Yes; upon initialization, the number 15 is stored in a special pointer memory address space.
2 Yes; a new memory space is allocated to hold the number 15.
3 No; this syntax is not allowed.
4 Yes; the pointer x points at the integer in memory location 15.
5 No; this assigns the number 15 to an unallocated space in memory.


43.
x[2] = 5 vs.
2[x] = 5

Are x[2] and 2[x] identical in the sample code above? Why or why not?

1 Yes; both are identical because they are resolved to pointer references.
2 Yes; both are identical because the compiler will identify the x variable and make adjustments.
3 No; x[2] is correct, but 2[x] is invalid syntax.
4 No; both variable assignments have invalid syntax.
5 No; 2[x] is correct, but x[2] is invalid syntax.


44.
Sample Code
int x=1;
int y=x+++ ++x;

Refer to the above sample code. What is the value of y?

1 2
2 3
3 4
4 5
5 The value is implementation dependent because it is not defined in Standard C.


45.
Which one of the following functions is the Standard C functional equivalent of the AT&T Unix function rindex(), which returns a pointer to the last occurrence of a character in a string or NULL if no such character exists?

1 strrchr()
2 stridx()
3 strcspn()
4 strchr()
5 strridx()


46.
Which one of the following declarations ensures that ptr CANNOT be used to modify the string to which it points (although ptr itself may be changed to point to another string)?
1 const char *ptr = "Hello";
2 char *ptr = const "Hello";
3 char * static ptr = "Hello";
4 static char *ptr = "Hello";
5 char * const ptr = "Hello";


47.
Sample Code
char * strdup (const char * s) {
char * buf;
int len;

assert(s != NULL);

len = strlen(s);
buf = (char *) calloc(len + 1, sizeof(char));
memcpy(buf, s, len);

return buf;
}

The proposed implementation of strdup() above contains a runtime error that may NOT appear consistently with each invocation. Which one of the following accurately describes this error?

1 The arguments to calloc() do not cause enough memory to be allocated for storing the contents of s.
2 If memory is scarce, calloc() may fail and return NULL. The code does not anticipate this condition.
3 memcpy() may corrupt data if used to copy ASCII strings.
4 buf is never NUL-terminated, and therefore cannot be used by C library functions affecting strings.
5 The function returns a pointer to dynamic memory. This practice should be avoided and always constitutes a memory leak.


48.
Sample Code
int a[5] = {1, 2, 3, 4, 5};
int *aPtr;
aPtr = a;
printf("element=%d\n", *(aPtr + 2));

What will be printed when the sample code above is executed?

1 element=1
2 element=2
3 element=3
4 element=4
5 element=5

9.
Sample Code
int my_func( int *a );

int main()
{
int b[3];
my_func( ???? );
return 0;
}

Referring to the sample code above, which one of the following must be inserted in place of the ???? to pass the array b to my_func?

1 (int *)b[0]
2 b
3 (int *)*b
4 (*b)[0]
5 *b

50.
Sample Code
void printTime( time_t *t )
{
????
}

Which one of the following can replace the ???? in the code above to print the time passed in t in human-readable form?

1 char s[ 100 ];
ctime( t, s );
printf( "%s\n", s );

2 printf( "%s\n", ctime( t ) );
3 printf( "%s\n", asctime( t ) );
4 printf( "%s", t );
5 char *s = ctime( t );
printf( "%s\n", s );
free( s );


51.
How do you declare a constant pointer to a constant string?

1 const* char const p;
2 const const char* p;
3 char const const* p;
4 const char const* p;
5 const char* const p;


52.
Sample Code #include
int ab=1;
int a=2;
int main(){
int b=3;
int ab=4;
printf("%i/*%i*/%i",a,b,ab);
}

Refer to the above sample code. What will be printed?

1 21
2 0/*4*/1
3 01
4 %i/*%i*/%i041
5 2/*3*/4


53.
Sample Code
int z;
int x = 5;
int y = -10;
int a = 4;
int b = 2;
z = x++ + ++y * b / a;

What number will z in the sample code above contain?

1 -3
2 -2
3 0
4 1
5 2


54.
Which one of the following functions allows an existing stream to be redirected?

1 setvbuf()
2 dup()
3 fopen()
4 popen()
5 freopen()


55.
Sample Code
int x = 0;

for ( ; ; )
{

if (x++ == 4) break;
continue;
}

printf("x=%d\n", x);

What will be printed when the sample code above is executed?

1 x=0
2 x=1
3 x=4
4 x=5
5 x=6


56.
Sample Code
/* Eliminate all whitespace from the end of s. */
void rtrim (char * s) {
char * start, ws, text;

start = s, ws = text = s - 1;

while (*s != '\0') {
if (isspace(*s)) {
ws = s;
while (isspace(*s)) s++;
} else {
text = s;
while (*s != '\0' && !isspace(*s)) s++;
}
}

if (ws > text) *ws = '\0';
}

The function rtrim(), defined above, contains an implementation error. Which one of the following describes it?

1 The comma operator has a higher precedence than assignment; this produces an unintended effect.
2 rtrim() does not correctly handle the case where no character of s is whitespace.
3 rtrim() does not correctly handle the case where every character of s is whitespace.
4 ws and text are not assignment-compatible with s or NULL.
5 The loop and its subordinate statements do not adequately detect an end-of-string condition on s in all cases.


57.
Sample Code
struct customer *ptr = malloc( sizeof( struct customer ) );
Given the sample allocation for the pointer "ptr" found above, which one of the following statements is used to reallocate ptr to be an array of 10 elements?
1 ptr = realloc( ptr, 10 * sizeof( struct customer ) );
2 realloc( ptr, 10 * sizeof( struct customer ) );
3 realloc( ptr, 9 * sizeof( struct customer ) );
4 ptr += malloc( 9 * sizeof( struct customer ) );
5 ptr = realloc( ptr, 9 * sizeof( struct customer ) );

58.
Sample Code
struct node {
int id;
int length;
struct node * next;
struct node * prev;
unsigned char data [1];
}

Consider struct node, an aggregate type defined above. Which one of the following might explain the declaration of its peculiar member data?

1 There is no difference between character unsigned char data and array unsigned char data [1], since each allocates only a single byte. Identical operations can be performed on both quantities. The choice was one of preference.
2 The programmer is declaring a bit field called data, which consists of only a single bit. struct node probably represents some hardware device.
3 data is probably used in conjunction with length and malloc() to create objects of variable size. struct node is essentially a header for an object of indeterminate size.
4 The information provided by the definition of struct node is insufficient to formulate a guess about the purpose of the member data or its strange declaration.
5 Clearly the programmer has made a typo. If the programmer had intended to allocate only a single byte, he or she would have declared data as unsigned char data instead.


59.
Sample Code
char ca[]="abc\012\0x34";

Refer to the above sample code. What does strlen(ca) return, using a Standard C compiler?

1 3
2 4
3 5
4 10
5 12


60.
sizeof(L"Hello world!") == x

Consider the code fragment above. For which value of x is the expression above true?

1 sizeof(char *)
2 sizeof(wchar_t [])
3 12
4 13
5 13 * sizeof(wchar_t);


61.
unsigned i, *ip = &i;
*ip = *ip & ~*ip;

What does the above sample code do?

1 It sets ip to 0.
2 It sets all the bits of i to 0.
3 It sets i to the value of UINT_MAX.
4 It sets ip to NULL.
5 It produces an undefined result.


62.
Sample Code
char*(*(*x)(void))[];

What does the above statement declare?

1 An array of pointers to a function with no parameters returning a pointer to a string pointer
2 An array of pointers to a pointer to a function with no parameters returning a string
3 A pointer to an array of functions with no parameters returning a string
4 A pointer to a function with no parameters that returns a pointer to an array of strings
5 It is a syntactically incorrect statement.


63.
#include
#include
void f(int x) {
char b[] = "1234567";
strncpy(b, "abc", x);
{
int i=0;
for(; i


64.
Sample Code
char c = '\101';

What will the variable c contain in the code above?

1 It will not compile.
2 The four characters '\', '1', '0', '1'
3 A backslash '\'.
4 65 (which is the letter A in ASCII)
5 101 (which is the letter e in ASCII)


65.
Sample Code
void myFunc (int x)
{
if (x > 0) myFunc(--x);
printf("%d, ", x);
}

int main()
{
myFunc(5);
return 0;
}

What will the above sample code produce when executed?

1 5, 4, 3, 2, 1, 0,
2 0, 0, 1, 2, 3, 4,
3 4, 3, 2, 1, 0, 0,
4 1, 2, 3, 4, 5, 5,
5 0, 1, 2, 3, 4, 5,


66.
Sample Code
char s1[100];
char s2[100];

gets( s1 );
fgets( s2, sizeof(s2), stdin);
printf( "%d\n", strlen( s1 ) - strlen( s2 ) );

What will be printed when the above code is executed and the string "abcd" is entered twice on stdin?

1 -1
2 0
3 1
4 2
5 4

67.
Which one of the following correctly declares a pointer to an array of 12 characters?
1 char (* a) [12];
2 char (* a) [11];
3 char * a [11];
4 char * (a [12]);
5 char * (a [11]);


68.
Sample Code
void zero_array (char a [20]) {
size_t size;

assert(a);

size = sizeof(a);
memset(a, 0, size);
}

The function zero_array(), defined above, contains an error. Which one of the following describes it?

1 The result of sizeof(a) may be subject to a type cast that causes size to acquire an erroneous value. The call to memset() will probably clear the wrong number of bytes.
2 The assert() macro may incorrectly cause the code to abort if the host machine uses a constant other than zero (0) to represent the null pointer natively.
3 Standard C does not permit programmers to declare the size of the leftmost dimension of an array parameter. The compiler should print an error when parsing zero_array().
4 sizeof(a) evaluates to sizeof(char *) rather than twenty (20). The call to memset() will probably clear the wrong number of bytes.
5 The second and third arguments to memset() are probably reversed.


69.
Sample Code
time_t currentTime = time( NULL );
printf("%s\n", ???? );

Which one of the following can replace ???? in order for the above sample code to print out the current time as a human-readable string?

1 ctime(¤tTime)
2 asctime(&currentTime)
3 asctime(currentTime)
4 timestr(currentTime)
5 strtime(currentTime)

70.
Sample Code
#include
static double (*funcs[])( double ) =
{
sin, cos, tan, asin, acos, atan, sinh, cosh, tanh
};

double computeTrigFunction( int index, double argument )
{
return ????;
}

Referring to the sample code above that should compute the value of a trigonometric function based on its index, what would be a replacement for the ???? to make the correct call?

1 *funcs[ index ]( argument )
2 (*funcs)[ index ]( argument )
3 funcs(argument)[index]
4 *(funcs[index](argument))
5 funcs[index](argument)


71.
Sample Code
file inc.h contains only the following line:
struct x {int d; char c;}

file main.c contains only the three following lines:

#include
#include "inc.h"
main(int n, char**a) { exit(0); }

Refer to the above sample code. The program is supposed to be Standard C. What is the problem with main in this code?

1 main does not return a value.
2 The parameters of main must be named argc and argv.
3 main is missing a return type.
4 The parameters of main are not used.
5 The type of the second parameter of main is invalid.


72.
Sample Code
int x = 5;
int y = 2;
char op = '*';
switch (op)
{
default : x += 1;
case '+' : x += y;
case '-' : x -= y;
}

After the sample code above has been executed, what value will the variable x contain?

1 4
2 5
3 6
4 7
5 8


1.
class A {
};

class B {
protected:
friend class A;
};

class C {
public:
friend class B;
};

Referring to the sample code above, assuming the above classes had data members, what names of C's members could be used in declarations of members of A?
1) Only private members
2) Only protected members
3) All of C's data members
4) Only public members
5) None of C's data members

courtesy:
DEVFYI - Developer Resource - FYI

Basic C Questions to test ur expertise -10

What are advantages and disadvantages of external storage class?

Advantages of external storage class
1)Persistent storage of a variable retains the latest value
2)The value is globally available
Disadvantages of external storage class
1)The storage for an external variable exists even when the variable is not needed
2)The side effect may produce surprising output
3)Modification of the program is difficult
4)Generality of a program is affected


What is a void pointer?

A void pointer is a C convention for a raw address. The compiler has no idea what type of object a void Pointer really points to. If you write
int *ip;
ip points to an int. If you write
void *p;
p doesn’t point to a void!
In C and C++, any time you need a void pointer, you can use another pointer type. For example, if you have a char*, you can pass it to a function that expects a void*. You don’t even need to cast it. In C (but not in C++), you can use a void* any time you need any kind of pointer, without casting. (In C++, you need to cast it).
A void pointer is used for working with raw memory or for passing a pointer to an unspecified type.
Some C code operates on raw memory. When C was first invented, character pointers (char *) were used for that. Then people started getting confused about when a character pointer was a string, when it was a character array, and when it was raw memory.


How can type-insensitive macros be created?

A type-insensitive macro is a macro that performs the same basic operation on different data types.
This task can be accomplished by using the concatenation operator to create a call to a type-sensitive function based on the parameter passed to the macro. The following program provides an example:

#include
#define SORT(data_type) sort_ ## data_type
void sort_int(int** i);
void sort_long(long** l);
void sort_float(float** f);
void sort_string(char** s);
void main(void);

void main(void)
{
int** ip;
long** lp;
float** fp;
char** cp;
...
sort(int)(ip);
sort(long)(lp);
sort(float)(fp);
sort(char)(cp);
...
}

This program contains four functions to sort four different data types: int, long, float, and string (notice that only the function prototypes are included for brevity). A macro named SORT was created to take the data type passed to the macro and combine it with the sort_ string to form a valid function call that is appropriate for the data type being sorted. Thus, the string
sort(int)(ip);
translates into
sort_int(ip);
after being run through the preprocessor.


When should a type cast not be used?

A type cast should not be used to override a const or volatile declaration. Overriding these type modifiers can cause the program to fail to run correctly.
A type cast should not be used to turn a pointer to one type of structure or data type into another. In the rare events in which this action is beneficial, using a union to hold the values makes the programmer’s intentions clearer.


When is a switch statement better than multiple if statements?

A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric type.


What is storage class and what are storage variable ?

A storage class is an attribute that changes the behavior of a variable. It controls the lifetime, scope and linkage.
There are five types of storage classes
1) auto
2) static
3) extern
4) register
5) typedef


What is a static function?

A static function is a function whose scope is limited to the current source file. Scope refers to the visibility of a function or variable. If the function or variable is visible outside of the current source file, it is said to have global, or external, scope. If the function or variable is not visible outside of the current source file, it is said to have local, or static, scope.


How can I sort things that are too large to bring into memory?

A sorting program that sorts items that are on secondary storage (disk or tape) rather than primary storage (memory) is called an external sort. Exactly how to sort large data depends on what is meant by too large to fit in memory. If the items to be sorted are themselves too large to fit in memory (such as images), but there aren’t many items, you can keep in memory only the sort key and a value indicating the data’s location on disk. After the key/value pairs are sorted, the data is rearranged on disk into the correct order. If too large to fit in memory means that there are too many items to fit into memory at one time, the data can be sorted in groups that will fit into memory, and then the resulting files can be merged. A sort such as a radix sort can also be used as an external sort, by making each bucket in the sort a file. Even the quick sort can be an external sort. The data can be partitioned by writing it to two smaller files. When the partitions are small enough to fit, they are sorted in memory and concatenated to form the sorted file.

What is a pointer variable?

A pointer variable is a variable that may contain the address of another variable or any valid address in the memory.


What is a pointer value and address?

A pointer value is a data object that refers to a memory location. Each memory locaion is numbered in the memory. The number attached to a memory location is called the address of the location.


What is a modulus operator? What are the restrictions of a modulus operator?

A Modulus operator gives the remainder value. The result of x%y is obtained by (x-(x/y)*y). This operator is applied only to integral operands and cannot be applied to float or double.


What is a macro, and how do you use it?

A macro is a preprocessor directive that provides a mechanism for token replacement in your source code. Macros are created by using the #define statement.
Here is an example of a macro: Macros can also utilize special operators such as the stringizing operator (#) and the concatenation operator (##).The stringizing operator can be used to convert macro parameters to quoted strings, as in the following example:
#define DEBUG_VALUE(v) printf(#v is equal to %d.n, v)
In your program, you can check the value of a variable by invoking the DEBUG_VALUE macro:
...
int x = 20;
DEBUG_VALUE(x);
...
The preceding code prints x is equal to 20. on-screen. This example shows that the stringizing operator used with macros can be a very handy debugging tool.


Differentiate between a linker and linkage?

A linker converts an object code into an executable code by linking together the necessary build in functions. The form and place of declaration where the variable is declared in a program determine the linkage of variable.


What is a function and built-in function?

A large program is subdivided into a number of smaller programs or subprograms. Each subprogram specifies one or more actions to be performed for a large program.such subprograms are functions.
The function supports only static and extern storage classes.By default, function assumes extern storage class.functions have global scope. Only register or auto storage class is allowed in the function parameters. Built-in functions that predefined and supplied along with the compiler are known as built-in functions.They are also known as library functions.


What is the difference between goto and longjmp() and setjmp()?

A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution.
Generally, a jump in execution of any kind should be avoided because it is not considered good programming practice to use such statements as goto and longjmp in your program.
A goto statement simply bypasses code in your program and jumps to a predefined position. To use the goto statement, you give it a labeled position to jump to. This predefined position must be within the same function. You cannot implement gotos between functions.
When your program calls setjmp(), the current state of your program is saved in a structure of type jmp_buf. Later, your program can call the longjmp() function to restore the program’s state as it was when you called setjmp().Unlike the goto statement, the longjmp() and setjmp() functions do not need to be implemented in the same function.
However, there is a major drawback to using these functions: your program, when restored to its previously saved state, will lose its references to any dynamically allocated memory between the longjmp() and the setjmp(). This means you will waste memory for every malloc() or calloc() you have implemented between your longjmp() and setjmp(), and your program will be horribly inefficient. It is highly recommended that you avoid using functions such as longjmp() and setjmp() because they, like the goto statement, are quite often an indication of poor programming practice.

s it acceptable to declare/define a variable in a C header?

A global variable that must be accessed from more than one file can and should be declared in a header file. In addition, such a variable must be defined in one source file.
Variables should not be defined in header files, because the header file can be included in multiple source files, which would cause multiple definitions of the variable. The ANSI C standard will allow multiple external definitions, provided that there is only one initialization. But because there’s really no advantage to using this feature, it’s probably best to avoid it and maintain a higher level of portability.
Global variables that do not have to be accessed from more than one file should be declared static and should not appear in a header file.


Why should I prototype a function?

A function prototype tells the compiler what kind of arguments a function is looking to receive and what kind of return value a function is going to give back. This approach helps the compiler ensure that calls to a function are made correctly and that no erroneous type conversions are taking place.


What is the quickest searching method to use?

A binary search, such as bsearch() performs, is much faster than a linear search. A hashing algorithm can provide even faster searching. One particularly interesting and fast method for searching is to keep the data in a digital trie. A digital trie offers the prospect of being able to search for an item in essentially a constant amount of time, independent of how many items are in the data set.
A digital trie combines aspects of binary searching, radix searching, and hashing. The term digital trie refers to the data structure used to hold the items to be searched. It is a multilevel data structure that branches N ways at each level.


What are the advantages of auto variables?

1)The same auto variable name can be used in different blocks
2)There is no side effect by changing the values in the blocks
3)The memory is economically used
4)Auto variables have inherent protection because of local scope


What are the characteristics of arrays in C?

1) An array holds elements that have the same data type
2) Array elements are stored in subsequent memory locations
3) Two-dimentional array elements are stored row by row in subsequent memory locations.
4) Array name represents the address of the starting element
5) Array size should be mentioned in the declaration. Array size must be a constant expression and not a variable.


How do you print only part of a string?

/* Use printf() to print the first 11 characters of source_str. */
printf(First 11 characters: ‘%11.11s’n, source_str);


In C, what is the difference between a static variable and global variable?

A static variable declared outside of any function is accessible only to all the functions defined in the same file (as the static variable). However, a global variable can be accessed by any function (including the ones from different files).


In C, why is the void pointer useful?

When would you use it? The void pointer is useful becuase it is a generic pointer that any pointer can be cast into and back again without loss of information.


courtesy:DEVFYI - Developer Resource - FYI

Basic C Questions to test ur expertise -9


Are pointers integers?

No, pointers are not integers.A pointer is an address.It is merely a positive number and not an integer.


How do you redirect a standard stream?

Most operating systems, including DOS, provide a means to redirect program input and output to and from different devices. This means that rather than your program output (stdout) going to the screen; it can be redirected to a file or printer port. Similarly, your program’s input (stdin) can come from a file rather than the keyboard. In DOS, this task is accomplished using the redirection characters, <>. For example, if you wanted a program named PRINTIT.EXE to receive its input (stdin) from a file named STRINGS.TXT, you would enter the following command at the DOS prompt:
C:> PRINTIT <) tells DOS to take the strings contained in STRINGS.TXT and use them as input for the PRINTIT program. The following example would redirect the program’s output to the prn device, usually the printer attached on LPT1: C :> REDIR > PRN
Alternatively, you might want to redirect the program’s output to a file, as the following example shows:
C :> REDIR > REDIR.OUT
In this example, all output that would have normally appeared on-screen will be written to the file
REDIR.OUT.
Redirection of standard streams does not always have to occur at the operating system. You can redirect a standard stream from within your program by using the standard C library function named freopen(). For example, if you wanted to redirect the stdout standard stream within your program to a file named OUTPUT.TXT, you would implement the freopen() function as shown here:
... freopen(output.txt, w, stdout);
...
Now, every output statement (printf(), puts(), putch(), and so on) in your program will appear in the file OUTPUT.TXT.


What is a method?

Method is a way of doing something, especially a systematic way; implies an orderly logical arrangement (usually in steps).


What is the easiest searching method to use?

Just as qsort() was the easiest sorting method, because it is part of the standard library, bsearch() is the easiest searching method to use. If the given array is in the sorted order bsearch() is the best method.
Following is the prototype for bsearch():
void *bsearch(const void *key, const void *buf, size_t num, size_t size, int (*comp)(const void *, const void*));
Another simple searching method is a linear search. A linear search is not as fast as bsearch() for searching among a large number of items, but it is adequate for many purposes. A linear search might be the only method available, if the data isn’t sorted or can’t be accessed randomly. A linear search starts at the beginning and sequentially compares the key to each element in the data set.


Is it better to use a pointer to navigate an array of values,or is it better to use a subscripted array name?

It’s easier for a C compiler to generate good code for pointers than for subscripts.


What is indirection?

If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable, or any other object in memory, you have an indirect reference to its value.


How are portions of a program disabled in demo versions?

If you are distributing a demo version of your program, the preprocessor can be used to enable or disable portions of your program. The following portion of code shows how this task is accomplished, using the preprocessor directives #if and #endif:
int save_document(char* doc_name)
{
#if DEMO_VERSION
printf(Sorry! You can’t save documents using the DEMO version of this program!n);
return(0);
#endif
...
}

What is modular programming?

If a program is large, it is subdivided into a number of smaller programs that are called modules or subprograms. If a complex problem is solved using more modules, this approach is known as modular programming.


How can you determine the maximum value that a numeric variable can hold?

For integral types, on a machine that uses two’s complement arithmetic (which is just about any machine you’re likely to use), a signed type can hold numbers from 2(number of bits 1) to +2(number of bits 1) 1. An unsigned type can hold values from 0 to +2(number of bits) 1. For instance, a 16-bit signed integer can hold numbers from 2^15 (32768) to +2^15 1 (32767).


How can you determine the maximum value that a numeric variable can hold?

How reliable are floating-point comparisons? Floating-point numbers are the black art of computer programming. One reason why this is so is that there is no optimal way to represent an arbitrary number. The Institute of Electrical and Electronic Engineers (IEEE) has developed a standard for the representation of floating-point numbers, but you cannot guarantee that every machine you use will conform to the standard.
Even if your machine does conform to the standard, there are deeper issues. It can be shown mathematically that there are an infinite number of real numbers between any two numbers. For the computer to distinguish between two numbers, the bits that represent them must differ. To represent an infinite number of different bit patterns would take an infinite number of bits. Because the computer must represent a large range of numbers in a small number of bits (usually 32 to 64 bits), it has to make approximate representations of most numbers.
Because floating-point numbers are so tricky to deal with, it’s generally bad practice to compare a floating-point number for equality with anything. Inequalities are much safer.


How can you determine the maximum value that a numeric variable can hold?

Which expression always return true? Which always return false? expression if (a=0) always return false
expression if (a=1) always return true


How many levels deep can include files be nested?

Even though there is no limit to the number of levels of nested include files you can have, your compiler might run out of stack space while trying to include an inordinately high number of files. This number varies according to your hardware configuration and possibly your compiler.


What is the difference between declaring a variable and defining a variable?

Declaring a variable means describing its type to the compiler but not allocating any space for it. Defining a variable means declaring it and also allocating space to hold the variable. You can also initialize a variable at the time it is defined.


How can I make sure that my program is the only one accessing a file?

By using the sopen() function you can open a file in shared mode and explicitly deny reading and writing permissions to any other program but yours. This task is accomplished by using the SH_DENYWR shared flag to denote that your program is going to deny any writing or reading attempts by other programs.
For example, the following snippet of code shows a file being opened in shared mode, denying access to all other files:
/* Note that the sopen() function is not ANSI compliant... */ fileHandle = sopen(“C:DATASETUP.DAT”, O_RDWR, SH_DENYWR);
By issuing this statement, all other programs are denied access to the SETUP.DAT file. If another program were to try to open SETUP.DAT for reading or writing, it would receive an EACCES error code, denoting that access is denied to the file.

How can I sort a linked list?

Both the merge sort and the radix sort are good sorting algorithms to use for linked lists.


Is it better to use malloc() or calloc()?

Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big:
void *malloc( size_t size );
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory at least big enough to hold them all:
void *calloc( size_t numElements, size_t sizeOfElement );
There’s one major difference and one minor difference between the two functions. The major difference is that malloc() doesn’t initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there you’re going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you’re going to use as a pointer is set to all zero bits. That’s usually a null pointer, but it’s not guaranteed.Anything you’re going to use as a float or double is set to all zero bits; that’s a floating-point zero on some types of machines, but not on all.
The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array.


What does it mean when a pointer is used in an if statement?

Any time a pointer is used as a condition, it means “Is this a non-null pointer?” A pointer can be used in an if, while, for, or do/while statement, or in a conditional expression.


Array is an lvalue or not?

An lvalue was defined as an expression to which a value can be assigned. Is an array an expression to which we can assign a value? The answer to this question is no, because an array is composed of several separate array elements that cannot be treated as a whole for assignment purposes.
The following statement is therefore illegal:
int x[5], y[5]; x = y;
Additionally, you might want to copy the whole array all at once. You can do so using a library function such as the memcpy() function, which is shown here:
memcpy(x, y, sizeof(y));
It should be noted here that unlike arrays, structures can be treated as lvalues. Thus, you can assign one structure variable to another structure variable of the same type, such as this:
typedef struct t_name
{
char last_name[25];
char first_name[15];
char middle_init[2];
} NAME;
...
NAME my_name, your_name;
...
your_name = my_name;


What is an lvalue?

An lvalue is an expression to which a value can be assigned. The lvalue expression is located on the left side of an assignment statement, whereas an rvalue is located on the right side of an assignment statement. Each assignment statement must have an lvalue and an rvalue. The lvalue expression must reference a storable variable in memory. It cannot be a constant.


Diffenentiate between an internal static and external static variable?

An internal static variable is declared inside a block with static storage class whereas an external static variable is declared outside all the blocks in a file.An internal static variable has persistent storage,block scope and no linkage.An external static variable has permanent storage,file scope and internal linkage.


What is the difference between a string and an array?

An array is an array of anything. A string is a specific kind of an array with a well-known convention to determine its length.
There are two kinds of programming languages: those in which a string is just an array of characters, and those in which it’s a special type. In C, a string is just an array of characters (type char), with one wrinkle: a C string always ends with a NUL character. The “value” of an array is the same as the address of (or a pointer to) the first element; so, frequently, a C string and a pointer to char are used to mean the same thing.
An array can be any length. If it’s passed to a function, there’s no way the function can tell how long the array is supposed to be, unless some convention is used. The convention for strings is NUL termination; the last character is an ASCII NUL (‘’) character.


What is an argument ? differentiate between formal arguments and actual arguments?

An argument is an entity used to pass the data from calling funtion to the called funtion. Formal arguments are the arguments available in the funtion definition.They are preceded by their own data types.Actual arguments are available in the function call.


courtesy:DEVFYI - Developer Resource - FYI

Basic C Questions to test ur expertise -8

What is the benefit of using const for declaring constants?

The benefit of using the const keyword is that the compiler might be able to make optimizations based on the knowledge that the value of the variable will not change. In addition, the compiler will try to ensure that the values won’t be changed inadvertently.
Of course, the same benefits apply to #defined constants. The reason to use const rather than #define to define a constant is that a const variable can be of any type (such as a struct, which can’t be represented by a #defined constant). Also, because a const variable is a real variable, it has an address that can be used, if needed, and it resides in only one place in memory


What is the easiest sorting method to use?

The answer is the standard library function qsort(). It’s the easiest sort by far for several reasons:
It is already written.
It is already debugged.
It has been optimized as much as possible (usually).
Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));


How many levels of pointers can you have?

The answer depends on what you mean by levels of pointers. If you mean How many levels of indirection can you have in a single declaration? the answer is At least 12.
int i = 0;
int *ip01 = & i;
int **ip02 = & ip01;
int ***ip03 = & ip02;
int ****ip04 = & ip03;
int *****ip05 = & ip04;
int ******ip06 = & ip05;
int *******ip07 = & ip06;
int ********ip08 = & ip07;
int *********ip09 = & ip08;
int **********ip10 = & ip09;
int ***********ip11 = & ip10;
int ************ip12 = & ip11;
************ip12 = 1; /* i = 1 */
The ANSI C standard says all compilers must handle at least 12 levels. Your compiler might support more.


Is it better to use a macro or a function?

The answer depends on the situation you are writing code for. Macros have the distinct advantage of being more efficient (and faster) than functions, because their corresponding code is inserted directly into your source code at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function. However, macros are generally small and cannot handle large, complex coding constructs. A function is more suited for this type of situation. Additionally, macros are expanded inline, which means that the code is replicated for each occurrence of a macro. Your code therefore could be somewhat larger when you use macros than if you were to use functions.
Thus, the choice between using a macro and using a function is one of deciding between the tradeoff of faster program speed versus smaller program size. Generally, you should use macros to replace small, repeatable code sections, and you should use functions for larger coding tasks that might require several lines of code.


What are the standard predefined macros?

The ANSI C standard defines six predefined macros for use in the C language:
Macro Name Purpose
_ _LINE_ _ Inserts the current source code line number in your code.
_ _FILE_ _ Inserts the current source code filename in your code.
_ _ Inserts the current date of compilation in your code.
_ _TIME_ _ Inserts the current time of compilation in your code.
_ _STDC_ _ Is set to 1 if you are enforcing strict ANSI C conformity.
_ _cplusplus Is defined if you are compiling a C++ program.


What is a const pointer?

The access modifier keyword const is a promise the programmer makes to the compiler that the value of a variable will not be changed after it is initialized. The compiler will enforce that promise as best it can by not enabling the programmer to write code which modifies a variable that has been declared const.
A const pointer, or more correctly, a pointer to const, is a pointer which points to data that is const (constant, or unchanging). A pointer to const is declared by putting the word const at the beginning of the pointer declaration. This declares a pointer which points to data that can’t be modified. The pointer itself can be modified. The following example illustrates some legal and illegal uses of a const pointer:
const char *str = hello;
char c = *str /* legal */
str++; /* legal */
*str = ‘a’; /* illegal */
str[1] = ‘b’; /* illegal */


What is a pragma?

The #pragma preprocessor directive allows each compiler to implement compiler-specific features that can be turned on and off with the #pragma statement. For instance, your compiler might support a feature called loop optimization. This feature can be invoked as a command-line option or as a #pragma directive.
To implement this option using the #pragma directive, you would put the following line into your code:
#pragma loop_opt(on)
Conversely, you can turn off loop optimization by inserting the following line into your code:
#pragma loop_opt(off)


What is #line used for?

The #line preprocessor directive is used to reset the values of the _ _LINE_ _ and _ _FILE_ _ symbols, respectively. This directive is commonly used in fourth-generation languages that generate C language source files.


What is the difference between text and binary modes?

Streams can be classified into two types: text streams and binary streams. Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline n character and vice versa. Binary streams are uninterpreted and are treated one byte at a time with no translation of characters. Typically, a text stream would be used for reading and writing standard text files, printing output to the screen or printer, or receiving input from the keyboard.
A binary text stream would typically be used for reading and writing binary files such as graphics or word processing documents, reading mouse input, or reading and writing to the modem.


How do you determine whether to use a stream function or a low-level function?

Stream functions such as fread() and fwrite() are buffered and are more efficient when reading and writing text or binary data to files. You generally gain better performance by using stream functions rather than their unbuffered low-level counterparts such as read() and write().
In multi-user environments, however, when files are typically shared and portions of files are continuously being locked, read from, written to, and unlocked, the stream functions do not perform as well as the low-level functions. This is because it is hard to buffer a shared file whose contents are constantly changing. Generally, you should always use buffered stream functions when accessing nonshared files, and you should always use the low-level functions when accessing shared files


What is static memory allocation and dynamic memory allocation?

Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.
Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.


When should a far pointer be used?

Sometimes you can get away with using a small memory model in most of a given program. There might be just a few things that don’t fit in your small data and code segments. When that happens, you can use explicit far pointers and function declarations to get at the rest of memory. A far function can be outside the 64KB segment most functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, so they’ll work no matter what code model the program uses.) A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are used with farmalloc() and such, to manage a heap separate from where all the rest of the data lives. If you use a small-data, large-code model, you should explicitly make your function pointers far.


What is the difference between far and near?

Some compilers for PC compatibles use two types of pointers. near pointers are 16 bits long and can address a 64KB range. far pointers are 32 bits long and can address a 1MB range.
Near pointers operate within a 64KB segment. There’s one segment for function addresses and one segment for data. far pointers have a 16-bit base (the segment address) and a 16-bit offset. The base is multiplied by 16, so a far pointer is effectively 20 bits long. Before you compile your code, you must tell the compiler which memory model to use. If you use a smallcode memory model, near pointers are used by default for function addresses.
That means that all the functions need to fit in one 64KB segment. With a large-code model, the default is to use far function addresses. You’ll get near pointers with a small data model, and far pointers with a large data model. These are just the defaults; you can declare variables and functions as explicitly near or far.
far pointers are a little slower. Whenever one is used, the code or data segment register needs to be swapped out. far pointers also have odd semantics for arithmetic and comparison. For example, the two far pointers in the preceding example point to the same address, but they would compare as different! If your program fits in a small-data, small-code memory model, your life will be easier.


When would you use a pointer to a function?

Pointers to functions are interesting when you pass them to other functions. A function that takes function pointers says, in effect, Part of what I do can be customized. Give me a pointer to a function, and I’ll call it when that part of the job needs to be done. That function can do its part for me. This is known as a callback. It’s used a lot in graphical user interface libraries, in which the style of a display is built into the library but the contents of the display are part of the application.
As a simpler example, say you have an array of character pointers (char*s), and you want to sort it by the value of the strings the character pointers point to. The standard qsort() function uses function pointers to perform that task. qsort() takes four arguments,
- a pointer to the beginning of the array,
- the number of elements in the array,
- the size of each array element, and
- a comparison function, and returns an int.


How are pointer variables initialized?

Pointer variable are initialized by one of the following two ways
- Static memory allocation
- Dynamic memory allocation


How can you avoid including a header more than once?

One easy technique to avoid multiple inclusions of the same header is to use the #ifndef and #define
preprocessor directives. When you create a header for your program, you can #define a symbolic name that is unique to that header. You can use the conditional preprocessor directive named #ifndef to check whether that symbolic name has already been assigned. If it is assigned, you should not include the header, because it has already been preprocessed. If it is not defined, you should define it to avoid any further inclusions of the header. The following header illustrates this technique:
#ifndef _FILENAME_H
#define _FILENAME_H
#define VER_NUM 1.00.00
#define REL_DATE 08/01/94
#if _ _WINDOWS_ _
#define OS_VER WINDOWS
#else
#define OS_VER DOS
#endif
#endif
When the preprocessor encounters this header, it first checks to see whether _FILENAME_H has been defined. If it hasn’t been defined, the header has not been included yet, and the _FILENAME_H symbolic name is defined. Then, the rest of the header is parsed until the last #endif is encountered, signaling the end of the conditional #ifndef _FILENAME_H statement. Substitute the actual name of the header file for FILENAME in the preceding example to make it applicable for your programs.

Difference between arrays and pointers?

- Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them
- Arrays use subscripted variables to access and manipulate data.Array variables can be equivalently written using pointer expression.


What are the advantages of the functions?

- Debugging is easier
- It is easier to understand the logic involved in the program
- Testing is easier
- Recursive call is possible
- Irrelevant details in the user point of view are hidden in functions
- Functions are helpful in generalizing the program


Is NULL always defined as 0?

NULL is defined as either 0 or (void*)0. These values are almost identical; either a literal zero or a void pointer is converted automatically to any kind of pointer, as necessary, whenever a pointer is needed (although the compiler can’t always tell when a pointer is needed).


What is the difference between NULL and NUL?

NULL is a macro defined in for the null pointer.
NUL is the name of the first character in the ASCII character set. It corresponds to a zero value. There’s no standard macro NUL in C, but some people like to define it.
The digit 0 corresponds to a value of 80, decimal. Don’t confuse the digit 0 with the value of ‘’ (NUL)! NULL can be defined as ((void*)0), NUL as ‘’.


Can the sizeof operator be used to tell the size of an array passed to a function?

No. There’s no way to tell, at runtime, how many elements are in an array parameter just by looking at the array parameter itself. Remember, passing an array to a function is exactly the same as passing a pointer to the first element.

Is using exit() the same as using return?

No. The exit() function is used to exit your program and return control to the operating system. The return statement is used to return from a function and return control to the calling function. If you issue a return from the main() function, you are essentially returning control to the calling function, which is the operating system. In this case, the return statement and exit() function are similar.


Can math operations be performed on a void pointer?

No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. By definition, if you have a void pointer, you don’t know what it’s pointing to, so you don’t know the size of what it’s pointing to. If you want pointer arithmetic to work on raw addresses, use character pointers.


Can the size of an array be declared at runtime?

No. In an array declaration, the size must be known at compile time. You can’t specify a size that’s known only at runtime. For example, if i is a variable, you can’t write code like this:
char array[i]; /* not valid C */
Some languages provide this latitude. C doesn’t. If it did, the stack would be more complicated, function calls would be more expensive, and programs would run a lot slower. If you know that you have an array but you won’t know until runtime how big it will be, declare a pointer to it and use malloc() or calloc() to allocate the array from the heap.


courtesy:DEVFYI - Developer Resource - FYI