Home > database >  Shallow copy of two arrays in C
Shallow copy of two arrays in C

Time:01-13

Is there a way to shallow copy the elements of a dynamically allocated array in C? Something like the following:

int size = 2;
int *arr1 = malloc(size*sizeof(int));
int *arr2 = malloc(size*sizeof(int));

arr1[0] = 1; arr1[1] = 2; // {1, 2}
arr2[0] = 3; arr2[1] = 4; // {3, 4}

// shallow copy here s.t. memadress(arr1[i]) == memadress(arr2[i])
// ...

arr1[0] = -1; // arr1 = {-1, 2} AND arr2 = {-1, 4}

CodePudding user response:

"Shallow" or "soft" copy typically just means copying a pointer but not the pointed-at data. As opposed to "hard" copy which also copies the pointed-at data. In your case, for example:

int *arr1 = malloc(size*sizeof(int));
int *arr2 = arr1; // "soft copy"

int* arr3 = malloc(size*sizeof(int);
memcpy(arr3, arr1, size*sizeof(int)); // "hard copy"

Or if you will:

int *arr1 = malloc(size*sizeof(int));
int *arr2 = malloc(size*sizeof(int));

arr1[0] = 1; arr1[1] = 2; // {1, 2}
arr2[0] = 3; arr2[1] = 4; // {3, 4}

free(arr2);
arr2 = arr1;

arr1[0] = -1; // {-1, 2} AND arr2 --> {-1, 4}

This doesn't make much sense, since it implies a soft copy of the elements not of the arrays. Such a container is likely needlessly complicated and not very useful. It could be done with an array of pointers, however:

#include <stdio.h>
#include <stdlib.h>

int main (void)
{

  int size = 2;
  int **arr1 = malloc(size*sizeof(int*));
  int **arr2 = malloc(size*sizeof(int*));

  // assign pointers to point at local compound literals:
  arr1[0] = &(int){1}; arr1[1] = &(int){2}; // {1, 2}
  arr2[0] = &(int){3}; arr2[1] = &(int){4}; // {3, 4}

  arr2[0] = arr1[0]; // "soft copy"
  *arr1[0] = -1;
  printf("arr1: {%d %d}\n", *arr1[0], *arr1[1]);
  printf("arr2: {%d %d}\n", *arr2[0], *arr2[1]);

  free(arr1);
  free(arr2);
}

Output:

arr1: {-1 2}
arr2: {-1 4}

But please avoid coming up with such obscure solutions just for the heck of it. Good programming = writing code as simple as possible.

  • Related