Could you explain what the next two lines do?
// Line 1
*(long *)add1= *(long *)add2;
// Line 2
*(int *)add1 = *(int *)add2;
Edit 1. I add the complete block of code of the function I test. PS It is only a part of the skript. [original Skript]
It is a custom memcpy function to copy block of memory from A to B.
(2)
while(word_left > 0){
*(char *)temp++ = *(char *)src++;
word_left --;
}
return (void *)dest;
}
Mr Vlag was so kind and explained what the lines in the part(1) mean.
My question is regarding to the part(2). This part should solve a problem if the memory address overlaps.
Why do we use char
here? Why can we not use long
or int
?
In the both records const6ructions ( long * )
and ( int * )
mean casting pointers correspondingly to pointer types long *
and int *
. Then these pointers are dereferenced *( long * )addr2
and *( int * )addr2
to get access to pointed objects values of which are assigned to other objects that are obtained also through casting and dereferencing pointers.
To make it more clear consider a demonstrative program.
#include <stdio.h>
int main(void)
{
int x = 10;
int y = 0;
printf( "x = %d, y = %d\n", x, y );
void *p1 = &x;
void *p2 = &y;
*( int * )p2 = *( int * )p1;
printf( "x = %d, y = %d\n", x, y );
return 0;
}
The program output is
x = 10, y = 0
x = 10, y = 10
In this program for example the pointer p1
of the type void *
due to the casting ( int * )p1
is interpreted as a pointer of the type int *
that points to an object of the type int
(in this case it points to the object x
). Now dereferencing this pointer *( int * )p1
you get a direct access to the pointed object x
.
You may not just write for example
y = *p1;
because you may not dereference a void pointer because the type void
is an incomplete type. So the compiler will not know how to interpret the pointed memory.