Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy one pointer content to another

Tags:

c

pointers

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);
}
like image 352
malajedala Avatar asked Oct 09 '16 00:10

malajedala


People also ask

How do you assign a value from one pointer to another?

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.

Can two pointers point to same address?

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 !

Does memcpy move the pointer?

memcpy does not modify any pointers; it only modifies the contents of the memory block pointed by the dst parameter.


1 Answers

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

like image 125
Anzurio Avatar answered Sep 22 '22 01:09

Anzurio