search

Home  >  Q&A  >  body text

c++ - memcpy函数形参指针类型能不能是char* ?

今天面试的时候被问到了。
我们知道memcpy传入的指针类型是void*。
但是由于复制的时候要一个个字节去复制,所以我们需要把void转换成char类型来处理。那么问题来了,我可不可以声明函数的时候就写成char*呢?

伊谢尔伦伊谢尔伦2806 days ago659

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 13:36:02

    C/C++ stipulates that any type of pointer can be converted into a void pointer, and a void pointer can be converted into a pointer of any type, so we can convert type into void , and then convert Convert void to char for memcpy. If the input parameter is defined as char, for types that cannot be converted invisibly by the compiler, the pointer type must be forced to char at the place of call.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:36:02

    What memcpy does is bit-wise copying, so it needs to be copied bit by bit. The char type only occupies one byte of space, so char is chosen for implementation. The parameter list uses void* to express that the parameter can be a pointer to any type.

    reply
    0
  • Cancelreply