memcpy:警告:取消引用"void *"指针 [英] memcpy: warning: dereferencing ‘void *’ pointer
问题描述
我使用read()函数从文件中读取40个字符,并且需要从10的偏移量复制20个字符的长度.换句话说,我需要将第10个字符至第30个字符进行memcpy转换为一个新的内存地址.但是,当我运行代码时(请参阅下文),我收到警告消息:warning: dereferencing ‘void *’ pointer
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:我找到了解决问题的方法:通过将缓冲区从void *转换为新的char *指针.
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:我在memcpy中找到了使用void *指针的方法:memcpy(new_container, buffer+10, 20)
;这样的变量缓冲区"可以是void *类型
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
推荐答案
更改行
memcpy(new_container, &buffer[10], 20);
到
memcpy(new_container, (char *)buffer + 10, 20);
这是因为&buffer[10]
的计算结果为&(*(buffer + 10))
,因为数组下标运算符的优先级高于address of
运算符&
.但是,buffer
的类型为void *
,并且由于没有大小信息,因此无法对void
指针执行指针算术运算.在buffer
上使用类型转换运算符(char *)
提供必要的大小信息,以使
(char *)buffer + 10
等效于buffer + 10 * sizeof(char)
或变量
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
.
这篇关于memcpy:警告:取消引用"void *"指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!