I use the read () function to read 40 characters from a file and you need to copy from offset 10 for length 20. In other words, I need to make memcpy from 10th to 30th character to a new memory address. However, when I run my code (see below), I received a 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); int bytes_read = read(fd, buffer, 40); void *new_container = malloc(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 to solve the problem: throwing the buffer from void * to a new char * pointer.
char *buffer2 = (char *) buffer; memcpy(new_container, &buffer2[10], 20);
edit2: I found a way to use the void * pointer in memcpy: memcpy(new_container, buffer+10, 20) ; the variable "buffer" can thus be of type void *
c file memcpy
Tonygw
source share