1

I think that copying elements of array like this:

unsigned char *new_bytes_array = malloc(sizeof(unsigned char)*length/2); 
for(int i=0, j=0; i<length; i++) {
  if(i % 2 == 0) continue; 
  new_bytes_array[j] = old_bytes_array[i]; 
  j++;

}

is making copy but value not by reference, but I would like to make sure that this will be deep copy not just shallow copy of references or pointers.

I know that this is maybe easy and ridiculous qustion, but I cannot find similar on stack rather memcpy() all array, but I want to copy only some elements for example every second element, or copy 1-3 elements and skip 4th element, (if i%4 == 0 skip element).

7
  • 1
    Your code makes a "deep copy" as is. Commented Sep 28, 2016 at 9:59
  • 1
    Note that sizeof (unsigned char) is always 1, so it's just an annoying way to write 1 (wihch in case of a multiplication is pretty pointless). Consider removing it. Commented Sep 28, 2016 at 10:59
  • @unwind actually on different platform, sizeof(unsigned char) is not always 1. So I think it's not a good idea to remove it. Commented Sep 28, 2016 at 12:07
  • @litao3rd No. You are mistaken, that's simply not true. The return value from sizeof is units of char, so by definition sizeof (char) is 1. Commented Sep 28, 2016 at 12:09
  • @unwind yep, sizeof(char) is not always 1 on different architecture. And sizeof is executed in compile time, so I think sizeof(unsigned char) is better than a magic number 1. Commented Sep 28, 2016 at 12:15

2 Answers 2

2

new_bytes_array[j] evaluates to an unsigned char.

Assuming old_bytes_array[i] does as well, then this

new_bytes_array[j] = old_bytes_array[i];

copies an unsigned char and not a pointer, not an unsigned char*.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, the assignment you show assigns a single unsigned char, i.e. "a byte" on most typical computers, it doesn't copy pointers but raw data.

Here's a complete function that does what you want, and fixes a few minor problems:

void * copy_every_second_byte(const void *src, size_t length)
{
  if(src == NULL || length == 0)
    return NULL;
  unsigned char *out = malloc(length / 2);
  for(size_t i = 0, j = 0; i < length; ++i)
  {
    if(i % 2 == 0) continue;
    out[j++] = ((unsigned char *) src)[i];
  }
  return out;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.