Michał Ziobro
Michał Ziobro

Reputation: 11822

C: unsigned char * bytes array copying elements to other unsigned char * array

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

Upvotes: 1

Views: 1615

Answers (2)

unwind
unwind

Reputation: 400109

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;
}

Upvotes: 0

alk
alk

Reputation: 70981

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

Upvotes: 2

Related Questions