memcpy: warning: dereferencing ‘void *’ pointer
c, file, memcpy
Solution
Change the line
memcpy(new_container, &buffer[10], 20);
to
memcpy(new_container, (char *)buffer + 10, 20);
That's because `&buffer[10]` evaluates to`&(*(buffer + 10))` because the array subscript operator has higher precedence than the `address of` operator `&`. However, `buffer` is of type `void *` and pointer arithmetic cannot be done on `void` pointers because there is no size information. Using the typecast operator `(char *)` on `buffer` provides the necessary size information so that `(char *)buffer + 10` is equivalent to `buffer + 10 * sizeof(char)` or the address of the `11`th element in the buffer pointed to by the variable `buffer`.
Problem
I use the read() function to read in 40 characters from a file, and need to copy from the offset of 10 for the length of 20. In other words, I need to do memcpy from the 10th to 30th characters into a new memory address. When I run my code (see following), however, I got the warning message: `warning: dereferencing ‘void *’ pointer` ``` int main() { void *buffer = malloc(40); int fd = open("example20.txt", O_RDONLY); printf("the value of fd is %d \n", fd); /* read 40 characters from the file */ int bytes_read = read(fd, buffer, 40); void *new_container = malloc(20); /* copy from buffer, starting offset at 10 for length of 20 */ memcpy(new_container, &buffer[10], 20); printf("new_container is %s \n", (char *) new_container); return 0; } ``` I am wondering what this error means, and how to fix it? edit1: I found a way of solving the problem: by casting the buffer from void* to a new char* pointer. ``` char *buffer2 = (char *) buffer; memcpy(new_container, &buffer2[10], 20); ``` edit2: I found a way of using void* pointer in memcpy: `memcpy(new_container, buffer+10, 20)`; the variable "buffer" in this way can be a void* type