user1051003
user1051003

Reputation: 1231

memcpy between 2 unsigned char* in c

How to copy use memcpy with two pointers a, b both are unsigned char *:

  1. a pointing to memory filled with data (unsigned char)
  2. b is even not allocated

How to copy a to b using memcpy? The third parameter of memcpy needs the size of the memory pointed to by a in bytes; how to get it?

Upvotes: 3

Views: 18278

Answers (3)

Ayub
Ayub

Reputation: 1009

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).

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.

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):

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

NOTE: strdup() is in POSIX. If you want strict ANSI C then you can make a wrapper like following as I mentioned earlier:

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 */
}

Upvotes: 3

selbie
selbie

Reputation: 104464

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". You can't reliably call memcpy If you don't know it or don't have it as a variable. Otherwise, any attempt to call memcpy is inherently unsafe.

What are you really trying to do?

It's also entirely possible that "a" is not an array at all. In which case you don't need memcpy:

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

Upvotes: 5

David W
David W

Reputation: 10184

Assuming "a" is null terminated, you should be able to use strlenb(a) to get its length, use calloc to allocate the memory for the destination pointer, then use memcpy as you noted.

Upvotes: 1

Related Questions