Home > database >  how I make that two variables points at the same spot in C ?
how I make that two variables points at the same spot in C ?

Time:11-22

I'm working with an array of objects where some of them should have the literal same parameter, so when it changes it also changes in all of them.

I tried using pointers, so that every parameter points at the same memory, but I really don't really know how to do it. In my code something is happening because it compiles, but when I change the variable that should change all at once, it change alone, I could change it all manually, but I don't think that is the optimal way of doing it.

ex: this line is to create the object, I give it the direction of memory of two nodes and a section,

elementos[i].Set_elemento(&nodos[numero_nodoi-1],&nodos[numero_nodoj-1],&secciones[numero_seccion-1]);

and here, I'm supposed to do the thing, but it doesn't do anything.

void Set_elemento(Nodo *nodo_i, Nodo *nodo_j, Seccion *seccion_){
            Nodo*p1=NULL;
            p1=&nodoi;
            p1=nodo_i;
            Nodo*p2=NULL;
            p2=&nodoj;
            p2=nodo_j;
            Seccion*j=NULL;
            j=&seccion;
            j=seccion_;
        }

thanks for your help and I'm sorry I don't speak English.

CodePudding user response:

To dereference a ponter, you use * before the pointer.

void Set_elemento(Nodo* nodo_i, Nodo* nodo_j, Seccion* seccion_) {
    nodoi = *nodo_i;
    nodoj = *nodo_j;
    seccion = *seccion_;
}

It gets the objects at the pointers' addresses and sets your member variables to them.

Though I think your entire method of achieving what you want to do is wrong.

Having each node store the entire node and copy it is very very... very dumb. Instead, you should store the addresses and allocate the pointers. Thus change your nodoi, nodoj, seccion member variables to pointers and you wouldn't need to dereference anything.

Then you could just copy the addresses (only 8 bytes) instead of dereferencing/copying the entire object and having to somehow keep track of all that for all nodes:

Nodo* nodoi, nodoj;
Seccion* seccion;
void Set_elemento(Nodo* nodo_i, Nodo* nodo_j, Seccion* seccion_) {
    nodoi = nodo_i;
    nodoj = nodo_j;
    seccion = seccion_;
}
  • Related