Qualcomm Interview Question
Applications DevelopersCountry: India
Interview Type: Phone Interview
why do we want to do char * ? I would think it rather this way :
return int ((&x+1) - &x);
simply because `char` always takes one byte, the basic unit of computer word (or world) :).
Question: Why does this fail when x is an array? Say int x[]={1, 2, 3, 4, 5};
Answer: Because x is a pointer to the very first value in the array, which is 1. Hence the sizeof x will return the size of the pointer, which is 4 or 8 bytes depending on the system.
/*
बंधुओं निम्न संगड़क प्रोग्राम में प्रिमिटिव डेटा टाइप जैसे int और char कि साइज़ प्राप्त करने का कोड विद्यमान है आगे का आप विस्तार कर सकते हैं.
ध्नयवाद
*/
#include <stdio.h>
#include <string.h>
int main()
{
int count = 0 ;
char Type[20] ;
char *DataType = Type;
printf("Enter Any Primitive Datatype: ");
gets(DataType);
if(!strcmp(DataType,"int"))
{
int a = 1;
while( a+1 != 1)
{
a = a<<1;
count++;
}
printf("Size of Int Is: %d Byte",count/8);
return(0);
}
else if(!strcmp(DataType,"char"))
{
char a = (char)1;
while((int)(a+1) != 1)
{
a = a<<1;
count++;
}
printf("Size of Char Is: %d Byte",count/8);
return(0);
}
}
Your Program will give a good results when we ask naming the datatype.. like 'int', 'char', what about if I write something like
int x=0;
int siz= sizeof(x);
Question doesn't makes sense. How does bitwise operator help in identifying 'size of operand?
to find size of any type
#define MYSIZEOF(x) ((char*)(&x+1) - (char*)&x)
x is a variable whose size you wish to find, it wont work if you pass 'typename' instead of variable
You need to grow up buddy.....you should rather say the question doesn't make sense to "you"
Hi Kutte londe,
Just now executed your program and checked step by step .. In while loop you are shifting bit to the left wards so every time it will increment by power of two i.e., 2,4,8,16.......-2147483648(value of 2^31) when you try to left shift the bit in 2^31 value there is no space for wiriting that much big value into the byte so 'a' becomes 0 and count value becomes 32 then coming out from loop.. you are dividing count 32 by 8[8 bits = byte] = 4........
Following solution has many limitation but I found only this using bit wize operator.
1. You can not return value as this is Macro with multiple line. (if you use function then you have to define type of argument)
2. You can not find size of float, double.
#define SizeOf(x) {\
x = 1;\
int i = 0;\
for (i=0;x!=0;i++) {\
x<<=1;\
}\
cout << i/8;\
}
int main ()
{
int x = 1;
cout << "sizeof int ";
SizeOf(x) ;
cout << endl;
return 0;
}
- n.j.joshi January 15, 2014