繁体   English   中英

复制结构指针到指针

[英]Copying for struct pointer to pointer

我很好奇为什么这样的代码会产生段错误

square->type=start.type

它们是相同类型的结构,square是指针,start不是。 我认为start.type中的值将被复制到正方形指向的类型部分。

有人可以解释段错误背后的原因吗?

这可能是以下原因之一:

  1. square为空。
  2. square不是空值,而是未初始化的,表示它没有指向有效的对象。
  3. 在执行该行之前删除了square ,这也意味着它没有指向有效的对象。
  4. type的重载赋值运算符出了点问题(如果type是一个类/结构并且其赋值运算符被重载)。
  5. start是一个参考,并通过将null递减来分配,例如:

     Apple *apple=0; Apple &start = *apple; 
  6. start是对某事物的引用,并且该事物已被删除,例如:

     Apple *apple=new Apple(); Apple &start = *apple; delete apple; square->type = start.type; // this line may not cause segfault but this is actually undefined behavior 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM