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.