Converting a pointer does not change the memory the pointer points to. Converting the c
to char [2]
or char (*)[2]
will not separate two characters from c
.
c
is char *
that points to the first character of "hello"
.
(char (*)[2]) c
says to take that address and convert it to the type “pointer to an array of 2 char
”. The result points to the same address as before; it just has a different type. (There are some technical C semantic issues involved in type conversions and aliasing, but I will not discuss those in this answer.)
memcpy(x,(char(*)[2])c,sizeof("hello"));
passes that address to memcpy
. Due to the declaration of memcpy
, that address is automatically converted to const void *
. So the type is irrelevant (barring the technical issues mentioned above); whether you pass the original c
or the converted (char (*)[2]) c
, the result is a const void *
to the same address.
sizeof "hello"
is 6, because "hello"
creates an array that contains six characters, including the terminating null character. So memcpy
copies six bytes from "hello"
into x
.
Then x[5]='\0';
is redundant because the null character is already there.
To copy n
characters from position p
in a string, use memcpy(x, c + p, n);
. In this case, you will need to manually append a null character if it is not included in the n
characters. You may also need to guard against going beyond the end of the string pointed to by c
.