Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my homespun sizeof operator need a char* cast?

Tags:

c

Below is the program to find the size of a structure without using sizeof operator:

struct MyStruct
{
  int i;
  int j;
};

int main()
{
   struct MyStruct *p=0;
   int size = ((char*)(p+1))-((char*)p);
   printf("\nSIZE : [%d]\nSIZE : [%d]\n", size);
   return 0;
}

Why is typecasting to char * required?

If I don't use the char* pointer, the output is 1 - why?

like image 537
aks Avatar asked Feb 02 '26 06:02

aks


1 Answers

Because pointer arithmetic works in units of the type pointed to. For example:

int* p_num = malloc(10 * sizeof(int)); 
int* p_num2 = p_num + 5;

Here, p_num2 does not point five bytes beyond p_num, it points five integers beyond p_num. If on your machine an integer is four bytes wide, the address stored in p_num2 will be twenty bytes beyond that stored in p_num. The reason for this is mainly so that pointers can be indexed like arrays. p_num[5] is exactly equivalent to *(p_num + 5), so it wouldn't make sense for pointer arithmetic to always work in bytes, otherwise p_num[5] would give you some data that started in the middle of the second integer, rather than giving you the sixth integer as you would expect.

In order to move a specific number of bytes beyond a pointer, you need to cast the pointer to point to a type that is guaranteed to be exactly 1 byte wide (a char).

Also, you have an error here:

printf("\nSIZE : [%d]\nSIZE : [%d]\n", size);

You have two format specifiers but only one argument after the format string.

like image 102
Tyler McHenry Avatar answered Feb 04 '26 18:02

Tyler McHenry