Thursday, July 9, 2009

C Interview Questions and Answers

Predict the output or error(s) for the following:
100.  main()

                        int a=10,*j;
            void *k; 
                        j=k=&a;
            j++;  
                        k++;
            printf("\n %u %u ",j,k);


Answer: 
Compiler error: Cannot increment a void pointer

Explanation:
Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type. No pointer arithmetic can be done on it and you cannot apply indirection operator (*) on void pointers.

101.    Printf can be implemented by using  __________ list.

Answer: 
Variable length argument lists

102.     char *someFun()
            {
            char *temp = “string constant";
            return temp;
            }
            int main()
            {
            puts(someFun());
            }

Answer:
string constant 

Explanation:
            The program suffers no problem and gives the output correctly because the character constants are stored in code/data area and not allocated in stack, so this doesn’t lead to dangling pointers.

103.     char *someFun1()
            {
            char temp[ ] = “string";
            return temp;
            }
            char *someFun2()
            {
            char temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};
            return temp;
            }
            int main()
            {
            puts(someFun1());
            puts(someFun2());
            }

Answer:
Garbage values.

Explanation:
            Both the functions suffer from the problem of dangling pointers. In someFun1() temp is a character array and so the space for it is allocated in heap and is initialized with character string “string”. This is created dynamically as the function is called, so is also deleted dynamically on exiting the function so the string data is not available in the calling function main() leading to print some garbage values. The function someFun2() also suffers from the same problem but the problem can be easily identified in this case.

104.  There were 10 records stored in “somefile.dat” but the following program printed 11 names. What went wrong?
void main()

{
struct student
{          
char name[30], rollno[6];
}stud;
FILE *fp = fopen(“somefile.dat”,”r”);
while(!feof(fp))
 {
                        fread(&stud, sizeof(stud), 1 , fp);
puts(stud.name);
}
}

Explanation:
fread reads 10 records and prints the names successfully. It will return EOF only when fread tries to read another record and fails reading EOF (and returning EOF). So it prints the last record again. After this only the condition feof(fp) becomes false, hence comes out of the while loop.

No comments:

Blog List