Thursday, July 9, 2009

In C if we give printf("the size is %d",sizeof('a')); instead giving 1 as output its giving 2 why? a is char

sizeof doesnt give the length of what you actually have, its gives the size of how big the variable has been declared to be . . .





sizeof will return the number of bytes reserved for a variable or data type.





The following code shows sizeof returning the length of a data type.








/* How big is an int? expect an answer of 4. */





main()


{


printf("%d \n", sizeof(int));


}














sizeof will also return the number of bytes reserved for a structure.








/* Will print 8 on most machines. */





main()


{


struct


{


int a;


int b;


} TwoInts;





printf("%d \n", sizeof(TwoInts));


}

















Finally, sizeof will return the length of a variable.








main()


{


char String[20];





printf ("%d \n", sizeof String);


printf ("%d \n", sizeof (String));


}

















In the example above I have printed the size of 'String' twice. This is to show that when dealing with variables, the brackets are optional. I recommend that you always place the brackets around the sizeof argument.


No comments:

Post a Comment