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