Home > Enterprise >  C: How to create a copy of a pointer to struct
C: How to create a copy of a pointer to struct

Time:01-28

I'm trying to figure out how I can create a copy of a pointer to struct inside a function. Let's say I have the following program:

struct Test
{
    int x;
};
void copyStruct(struct Test **testPtr);

int main(){
struct Test *myPtr = malloc(sizeof(struct Test));
myPtr->x = 111;
printf("Before copyStructOne x is: %d\n", myPtr->x);

copyStruct(&myPtr);

// I want this to print 111 not 500
printf("After copyStructOne x is: %d\n", myPtr->x);

return 0;
}

void copyStructOne(struct Test **testPtr)
{
    //I thought this would create a local copy of what is in *testPtr
    struct Test *testStr = (*testPtr); 

    //and this would modify only the local copy
    testStr->x = 500;
    printf("Inside copyStructOne x is: %d\n", testStr->x);
}

How can I have the final printf() inside main() print 500 and not 111?

CodePudding user response:

You do in fact have a copy of a pointer to a struct in the copyStructOne function. However, the two pointers, because they contain the same pointer value, both point to the same instance of a struct.

If what you actually want is a copy of the struct, then copy the struct instead of the pointer.

void copyStructOne(struct Test **testPtr)
{
    struct Test testStr = **testPtr; 

    testStr.x = 500;
    printf("Inside copyStructOne x is: %d\n", testStr.x);
}
  •  Tags:  
  • Related