C:如何创建指向结构的指针的副本

C: How to create a copy of a pointer to struct

我想弄清楚如何在函数内部创建指向结构的指针的副本。假设我有以下程序:

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);
}

如何让 main() 中的最终 printf() 打印 500 而不是 111

您实际上在 copyStructOne 函数中有一个指向结构的指针的副本。但是,这两个指针,因为它们包含相同的指针值,所以都指向结构的相同实例

如果您真正想要的是结构的副本,则复制结构而不是指针。

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

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