© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

10. Can math operations be performed on a void pointer?

Ans:
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.

Ex - 1:  What is the output?
main()
{
                        int i=300;
            char *ptr = &i;
                        *++ptr=2;
            printf("%d",i);
}

Ans:
556

Explanation:

The integer value 300  in binary notation is: 00000001 00101100. It is  stored in memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory representation as: 00101100 00000010. So the integer corresponding to it  is  00000010 00101100 => 556.

Ex - 2 what is the output?:

#include
main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
                  least = (*ptr
printf("%d",least);
}

Ans:
0

Explanation:  

After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘\0’. So the value of ‘str’ is less than that of ‘least’. So the value of ‘least’ finally is 0.


SLogix Student Projects
bottom