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:
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);
}
Pointer assignment between two pointers makes them point to the same pointee. So the assignment y = x; makes y point to the same pointee as x . Pointer assignment does not touch the pointees. It just changes one pointer to have the same reference as another pointer.
Yes two pointer variable can point to the same memory address. The same applies to linked list address. Your variable “p” and “temp” would point to the same memory address now !
memcpy does not modify any pointers; it only modifies the contents of the memory block pointed by the dst parameter.
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;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With