【问题标题】:Is there a way to make a shallow copy of a constant struct to a non-constant struct? [closed]有没有办法将常量结构的浅拷贝复制到非常量结构? [关闭]
【发布时间】:2016-02-15 00:26:08
【问题描述】:

我想对具有恒定减速的整个结构进行浅拷贝。但是我希望我复制的结构也不是恒定的。

这是我迄今为止所做的,但会产生错误:

struct Student{
    char *name;
    int age;
    Courses *list;  //First course (node)
}Student;

void shallowCopy(const Student *one){
    Student oneCopy = malloc(sizeof(one));

    oneCopy = one;     <--------------- ERROR POINTS TO THIS LINE
}

我得到的编译器错误:

Assignment discards 'const' qualifier from pointer target type.

我知道我可以从其中删除const 或将const 添加到oneCopy,但我想知道在Student one 是const 和副本 Student oneCopy 不是。

【问题讨论】:

  • 为什么投反对票?这不是一个有效的、独特的问题,它显示了我的尝试吗?
  • 我没有投票,但 -1 可能是因为这里有一些非常基本的错误,任何介绍性书籍或课程都会涵盖这些错误。此外,您没有发布您的实际代码:您应该在void shallowCopy(const Student *one){ 行上得到一个编译错误;另一个在malloc 行上,在指示的行上出现另一个错误。

标签: c struct constants shallow-copy


【解决方案1】:

应该是:

Student* oneCopy = malloc(sizeof(*one));
*oneCopy = *one;

因为你要分配的是结构体,而不是指针。

【讨论】:

  • 你真的不需要malloc() 电话。直接分配也可以:Student two = *one;.
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 2021-03-07
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多