malajedala malajedala - 1 month ago 7
C Question

Copy one pointer content to another

I thought I've read somewhere that when using pointers and we want to copy the content of one to another that there are two options:


  • using memcpy or

  • just assigning them with = ?



However in the lower example, I just tested it by allocating memory for two pointers, then assigning the second, changing first..but then the entry of my second pointer is also changing.. What am I doing wrong :/.

typedef struct {

int a;
int b;
int c;
} my_struct;


int main(int argc, char** argv) {

my_struct* first = malloc(sizeof(my_struct));
first->a = 100; first->b = 101; first->c = 1000;

my_struct* bb = malloc(sizeof(my_struct));

printf("first %d %d %d\n", first->a, first->b, first->c);
bb = first;
printf("second %d %d %d\n", bb->a, first->b, bb->c);


first->a = 55; first->b = 55; first->c = 89;
printf("second %d %d %d\n", bb->a, first->b, bb->c);
}

Answer

The moment you do bb = first;, bb and first are pointing to the same location of memory. first->a = 55; first->b = 55; first->c = 89; will change the values for a, b, and c in that location. The original value of first, is still lingering in memory but no way to access it anymore.

I think what you may want to do is *bb = *first;.