我使用read()函数从文件中读取40个字符,并需要从第10个字符偏移处复制20个字符。换句话说,我需要将第10到30个字符从原始内存地址复制到新的内存地址中。当我运行以下代码时,却出现了警告信息:
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;
}
我想知道这个错误是什么意思,以及如何修复它?
编辑1:我发现了一个解决问题的方法:通过将缓冲区从void*转换为新的char*指针。
char *buffer2 = (char *) buffer;
memcpy(new_container, &buffer2[10], 20);
编辑2:我找到了一种在memcpy中使用void*指针的方法:memcpy(new_container, buffer+10, 20)
;这种方式中的变量"buffer"可以是void*类型
buffer+10
其中buffer
是void*
,没有具体类型可用于执行指针算术运算。gcc
会这样做,但这不是标准的。为了符合标准,您需要使用一个有类型的指针或在算术运算之前将其强制转换为有类型的指针类型(请参见ajay的答案以获取此类转换,本答案仅使用有类型的指针)。 - WhozCraig