Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shallow copy of two arrays in C

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}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading