When we were preparing for the interviews in College days, nothing was in mind except interviews. Also we were no thinking beyond the interview requirements. But when we face the same type of situations while working in any project that will make us to understand our present and past understanding capabilities and also make us to know more.
When I was in 6th sem of my engineering, I was attended an interview of RoboSoft, UDUPI. While preparing for that, I came across a C question as follows.
#include "stdio.h"
void main()
{
int a=10, b=20;
int *ptr = &a;
ptr--;
printf("%d", *ptr);
}
This will print as 20. Also this may depends on compilers. Assume GCC for this.
When local variables are declared, will be pushed into the stack in order of their declaration. Stack address will increment from TOP(decrement from BOTTOM). Here initially ptr will point to a's location and when we decrement it will point to b's location.
Lets come to point. I have following type of declarations.
struct abc
{
union data xyz;
int i;
};
In my program, I was written as follows.
uinon data a;
int temp = 10;
printf("%d", temp);
memset(a, 0, sizeof(struct abc));
printf("%d", temp);
While testing my code, I was getting the value of temp is 10 and 0 both. Initially I was wondering how temp value is changing without doing anything. After sometime, I understood that memset is making temp 0..!!!?? But how ?
Then, due to my interview question, I closely looked into the memset statement and its declaration and came to know how memset was making the temp variable 0. Because, structure is having sizeof union +1 and hence next immediate 32 bit is setting to 0.
After knowing this, I was very happy and was feeling like anything for that point of time.
This is what will make us our work enjoyable to some extent and thats what i expected from this industry.
Happy moment...!! gUd lUcK...
No comments:
Post a Comment