简体   繁体   中英

what is the difference between allocation for a pointer, and allocation to element or struct?

I'm having a trouble understanding the difference between those two :

typedef struct someStruct{
   int x;
   char *name;
   struct someStruct *next
}TEST1,*pTEST1;

void *copyElement(void* s){
   pTEST1 cop = (pTEST1)calloc(1,sizeof(TEST1));
   cop = (pTEST1)s;
}

this one if I'm not mistaken is pointing on the same element so if I'm changing one, all the pointed elements will change

I want to create a new copy of the element , in a new "place" in the memory and to point on it.

would love to get explanation.

Another thing I don't get is the difference between allocation space for pointer and the object itself.

For example if I take my function and do that:

void *copyElement(void* s){
    pTEST1 cop = (pTEST1)calloc(1,sizeof(TEST1));
    cop = (pTEST1)s;
    /*or */
    TEST1 a;
    pTEST1 b;
    a.x  =(pTEST1)s->x;
    a.name = (pTEST1)s->name;
    a->next = (pTEST1)s->next;

    b= &a ;
    // it means the when the function ends,
    // I loose the pointer ? because I didn't
    // allocate space for it?
}

The pTEST1 identifier is just a type name alias, it means "pointer to TEST1 structure". Some C programmers swear by it, some think it is evil because it hides pointers and doesn't make it clear when you need to dereference them. Which is exactly what's wrong with your code, you didn't actually copy the structure, you only copied the pointer. A proper version ought to resemble this:

void *copyElement(void *s){
   // Copies element pointed-to by "s".  NOTE: free() required on the returned pointer
   TEST1 *copy = malloc(sizeof(TEST1));
   *copy = *(TEST1*)s;
   return copy;
}

If you really want to use pTEST1 then just substitute TEST1* in the above snippet with it. Note that there is no point in using calloc() when you are going to overwrite the allocated memory anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM