简体   繁体   English

在c中2个unsigned char *之间的memcpy

[英]memcpy between 2 unsigned char* in c

How to copy use memcpy with two pointers a , b both are unsigned char * : 如何复制使用memcpy与两个指针ab都是unsigned char *

  1. a pointing to memory filled with data (unsigned char) a指向存储器填充数据(无符号字符)
  2. b is even not allocated b甚至没有分配

How to copy a to b using memcpy ? 如何使用memcpya复制到b The third parameter of memcpy needs the size of the memory pointed to by a in bytes; 的第三个参数memcpy需要的存储器的大小指向a以字节为单位; how to get it? 怎么弄明白?

unsigned char* b = (unsigned char*)malloc(length_of_a);
memcpy(b, a, length_of_a);

Of course, I can't tell you how to get the length of "a". 当然,我不能告诉你如何获得“a”的长度。 You can't reliably call memcpy If you don't know it or don't have it as a variable. 您无法可靠地调用memcpy如果您不知道或不将其作为变量。 Otherwise, any attempt to call memcpy is inherently unsafe. 否则,任何调用memcpy的尝试本质上都是不安全的。

What are you really trying to do? 你真的想做什么?

It's also entirely possible that "a" is not an array at all. 完全可能“a”根本不是数组。 In which case you don't need memcpy: 在这种情况下,您不需要memcpy:

char b = '\0';
if (a != NULL)
{
    b = *a;
}

We must assume that a is NUL terminated (ending with '\\0' ), otherwise we can't be sure about its size/length (unless you know the length of a yourself). 我们必须假设, a是NUL终止(结尾'\\0' ),否则我们不能确定它的大小/长度(除非你知道的长度a自己)。

char *a = "Hello World"; /* say for example */
size_t len = strlen(a)+1; /* get the length of a (+1 for terminating NUL ('\0') character) */

Note that, if you know the length of the string pointed to by (or saved in) a then you will assign it to len , instead of using the above statement. 请注意,如果您知道(或保存在) a指向的字符串的长度,则将其分配给len ,而不是使用上述语句。

char *b = calloc(1, len); /* */
memcpy(b, a, len); /* now b contains copy of a */

If your intention is just to make a copy of a string (NUL terminated), you can use strdup() (declared in string.h ): 如果你的意图只是制作一个字符串的副本(NUL终止),你可以使用strdup() (在string.h声明):

char *b = strdup(a); /* b now has a copy of a */

NOTE: strdup() is in POSIX. 注意: strdup()在POSIX中。 If you want strict ANSI C then you can make a wrapper like following as I mentioned earlier: 如果你想要严格的ANSI C,那么你可以像我之前提到的那样创建一个像下面这样的包装器:

unsigned char *my_strdup(const unsigned char *a)
{
  size_t len = strlen(a)+1;
  unsigned char *b = calloc(1, len);
  if (b) return (unsigned char *) memcpy(b, a, len);
  return NULL; /* if calloc fails */
}

假设“a”为空终止,您应该能够使用strlenb(a)来获取其长度,使用calloc为目标指针分配内存,然后使用你记下的memcpy。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM