将没有长度的指针作为目的地传递给memcpy是否合法?

我想知道我可以使用不带字符的char指针作为memcpy中的目标。 示例:我想将具有特定大小的定义长度的char数组中的数据复制到另一个数组中,但是我想将其定义为没有特定大小的指针。

char * ptr_1;
char arr[4] = "Data";
memcpy(ptr_1, arr, 4); // IS it allowed to do this?
评论
  • matque
    matque 回复

    No, you can't do that. If you do that, it would invoke undefined behavior as the address pointed by ptr_1 is in determinant and you don't own it.

    您可以分配静态存储空间来复制结果,也可以动态分配存储空间。