Infosys Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
your answer is wrong ,which book or crap r u following????
with your code answer is 1 for integer ......... bcoz of pointer arithmetic......
The logic is absolutely correct, but what I think (long int ) as a cast would be better, as the address, for a 64 bit machine would be bigger than the limit of int
#include <stdio.h>
#define mysizeof(type) (int)(&type+1)-(int)(&type)
struct temp
{
char *a;
int b;
float d[4];
};
int main()
{
int a;
char *p;
char b[5];
int d[10];
float c;
struct temp temp1;
printf("Size of p = %d \n",(int)(&a+1)-(int)(&a));
printf("Size of a = %d \n",sizeof(a));
printf("Size of a = %d \n",mysizeof(a));
printf("Size of p = %d \n",mysizeof(p));
printf("Size of b = %d \n",mysizeof(b));
printf("Size of d = %d \n",mysizeof(d));
printf("Size of c = %d \n",mysizeof(c));
printf("Size of Struct Size temp1 = %d \n",sizeof(temp1));
printf(" MyStruct Size = %d \n",mysizeof(temp1));
}
o/p:-
Size of p = 4
Size of a = 4
Size of a = 4
Size of p = 4
Size of b = 5
Size of d = 40
Size of c = 4
Size of Struct Size temp1 = 24
MyStruct Size = 24
It can be found through following ways:
1. pointer airthmatic that is take pointer of same type, increment it and get difference between 2 memory addresses.
2. by storing largest value. Assume its integer and try to store number 2^n starting from 0. Compare stored value with original number.
If it is same, icrement number otherwise stop and n is the bit size of this data type.
3. Through shift operation. Intially set variable to -1. Then do right shift untill you getback number equal to 0.
Count how many times you shifted. This is the size of variable in bits.
#include<stdio.h>
void main()
{
int x[2];
long int xa[2];
float y[2];
double z[2];
char *a,*b;
a=(char *)&x[0];
b=(char *)&x[1];
printf("size of int=%d\n",b-a);
a=(char *)&xa[0];
b=(char *)&xa[1];
printf("size of long double=%d\n",b-a);
a=(char *)&y[0];
b=(char *)&y[1];
printf("size of float=%d\n",b-a);
a=(char *)&z[0];
b=(char *)&z[1];
printf("size of double=%d\n",b-a);
}
- ashot madatyan June 20, 2012