How to copy a structure pointer?

Asked

Viewed 122 times

2

Is it possible to clone a structure pointer? Follow the code:

typedef struct{
    int numero;
}estrutura;

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

    estrutura *i = (estrutura *)malloc(sizeof(estrutura));
    estrutura *d;

    i->numero = 5;

    printf("%d", i->numero);

}

I want the structure *d for example be the copy of the structure *i, so that if I change the value of i->numero, does not interfere with d->numero.

1 answer

3


The first thing you need to do is allocate memory to the other structure. Then you should copy with memcpy().

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

typedef struct {
    int numero;
} Estrutura;

int main(int argc, char *argv[]){
    Estrutura *i = malloc(sizeof(Estrutura));
    Estrutura *d = malloc(sizeof(Estrutura));
    i->numero = 5;
    memcpy(d, i, sizeof(Estrutura));
    i->numero = 6;
    printf("%d", d->numero);
    printf("%d", i->numero);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Note that you are copying the content of the object, because the pointer is always copied naturally.

  • I did it this way, but I didn’t allocate memory to *d, I did the direct memcpy, it could cause some problem ?

  • Where did you copy the object then?

  • I did the following, memcpy(d, i, sizeof(structure));, without using malloc in *d

  • That doesn’t answer the question I asked.

  • From what I understand, when I used memcpy, I copied what was in the structure i to d. But you asked me to do a malloc on the structure d before using the memcpy command. I made the memcpy without making this malloc for structure d and it worked, I wonder if it can cause any problem ?

  • You still haven’t answered the question I asked. What is the location of the memory where this object was copied?

  • Sorry I don’t know if I understood your question correctly, it would be in the heap ?

  • And how can you put an object in heap? Or else, where the heap?

  • Making the allocation, right ?

  • 3

    Exactly! And if you don’t make the allocation you go where?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.