I came through this program to find length of a struct without using sizeof. I have some questions that I could not find answers.
I cannot understand this step
(char*)(p+1)-(char*)p)- why the pointer is type casted into char.I printed out size of each datatypes. So, the size of the structure should have been 3* size of int + size of float + size of char = 17. However, size of the struct is 20. Please explain how.
Why the output is 5 for
(float*)(p+1)-(float*)p).
Code:
#include<stdio.h>
struct sample
{
int a,b;
float c;
char z;
int k;
};
void main()
{
struct sample *p;
struct sample x;
printf("size of struct w/o using sizeof: %d\n", (char*)(p+1)-(char*)p);
printf("size of struct w/o using sizeof: %d\n", (float*)(p+1)-(float*)p);
printf("size of struct using sizeof: %d\n", sizeof(struct sample));
printf(" %d %d %d %d\n", sizeof(char), sizeof(int), sizeof(float), sizeof(x));
}
Output:
size of struct w/o using sizeof: 20
size of struct w/o using sizeof: 5
size of struct using sizeof: 20
1 4 4 20
4) Thank you for your answers. I have one more doubt.
code
struct sample
{
int a,b;
float c;
char z;
int k;
char s;
};
After padding, the size of this struct would be 24 bytes. Why printing this in float (float)((float*)(p+1)-(float*)p) does not give 5.8000 instead of 6.
p+1without casting, i.e. how are you making this work at all? What issizeof(char)? What issizeof(float)? - Rup