【问题标题】:How do I copy structures using pointers to structures?如何使用指向结构的指针复制结构?
【发布时间】:2015-07-01 05:49:05
【问题描述】:

我需要使用相应的结构指针将结构的一个实例复制到另一个实例。我试过的代码如下:

typedef struct{
int a, b, c;} test;

int main(){
test *q, *w;
(*w).a = 2;
(*w).b = 3;
(*w).c = 4;

printf("\n%d\n%d\n%d", (*w).a, (*w).b, (*w).c);

memcpy((void*)q, (void*)w, sizeof(test));

printf("\n%d\n%d\n%d", (*q).a, (*q).b, (*q).c);

return 0;

我得到的输出是:

2
3
4
1875984
32768
1296528

谁能告诉我如何复制结构?我需要使用指向结构的指针,只需这样做:

test w, q;
q = w;

对我的程序来说是不够的。

谢谢。

【问题讨论】:

    标签: pointers structure copying


    【解决方案1】:

    替换代码中的行:

    memcpy((void*)q, (void*)w, sizeof(test));
    

    下面一行:

    memcpy((void*)&q, (void*)&w, sizeof(test));
    

    【讨论】:

    • 我试过这个。程序显示运行时错误 - 它没有运行完成。感谢您的回答 - 还有其他想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2020-09-12
    相关资源
    最近更新 更多