Why does my homespun sizeof operator need cast char *?

The following is a program for determining the size of a structure without using the 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 typginging required for char *?

If I do not use the char * pointer, the output will be 1 - why?

+3
source share
4 answers

Because pointer arithmetic works in units of the specified type. For instance:

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

p_num2 p_num, p_num. , , p_num2, , p_num. , . p_num[5] *(p_num + 5), , p_num[5] , , , , .

, , 1 (a char).

, :

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

, .

+2

char *, 1 - ?
operator- , operator+. sizeof(MyStruct), , sizeof(MyStruct) operator- .

sizeof()?

+2

. .

int* p;
p + 5; // this is implicitly p + 5 * sizeof(int)

char *, .

+2

. , () - *(ptr+n) ptr[n]. , , . pointer to char , . C char byte (.. , char), , .

+1

Source: https://habr.com/ru/post/1740466/


All Articles