Sunday, August 19, 2018

C Questions And Answers – 2018C19

There are many commonly asked questions regarding C programming language. Below are some collected such question-answer examples. The questions are usually related with 32-bit system, Turbo C IDE in windows or GCC under Linux environment [not always].

For more such examples, click C_Q&A label.

Predict the output or error(s) for the following:

 

-------------------------------------------------------------------------------------------------

 

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.

 

-------------------------------------------------------------------------------------------------

 

main()

{

extern int i;

{

 int i=20;

{

     const volatile unsigned i=30; printf("%d",i);

     }

     printf("%d",i);

     }

printf("%d",i);

}

int i;

 

-------------------------------------------------------------------------------------------------

 

                   Printf can be implemented by using __________ list.

 

Answer:

Variable length argument lists

 

-------------------------------------------------------------------------------------------------

 

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.

 

-------------------------------------------------------------------------------------------------

 

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.

 

-------------------------------------------------------------------------------------------------

 

…till next post, bye-bye & take care.

No comments:

Post a Comment