简体   繁体   中英

What parameters would I put in this function 'copy' to copy a to b?

struct info
{
    int val;
};

void copy(struct info ** dst, struct info * src)
{
    *dst = (struct info *)malloc(sizeof(struct info));
    **dst = *src;
}

int main()
{
    struct info *a, *b; 

    a = (struct info *)malloc(sizeof(struct info));
    a -> val = 7;
    copy( , );

    a -> val = 9;
    printf("%d", b->val);
}

I have tried (b, a) , (*b, *a) , (b, *a) and so one but the argument is always unexpected by the compiler. Have been trying for an hour with no result - just a half melted brain.

The first argument is supposed to be a pointer to a pointer. Since b is a pointer, you need to take its address, which is &b .

The second argument is supposed to be a pointer. a is a pointer, so you just pass it directly.

copy(&b, a);

* is for indirecting through a pointer to access what it points to. That's the exact opposite of what you want, which is to get a pointer to the variable itself. You use * inside the copy function to access what the pointers given point to.

BTW, you should also see Do I cast the result of malloc?

And don't forget to free the structures when you're done using them.

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