【问题标题】:what if we assign different structures with = operator instead of memcpy()如果我们用 = 运算符而不是 memcpy() 分配不同的结构怎么办
【发布时间】:2014-06-13 22:25:57
【问题描述】:

如果执行以下代码,data1的内容是什么?

struct {
int a;
char b;
}st1;

struct {
char c;
int d;
}st2;

main()
{
    struct st1 data1 = {0};
    struct st2 data2 = {'A',10};
    data1 = data2;
}

【问题讨论】:

  • 你的代码不是有效的 Ansi 代码,你必须说 struct st1 {...}, struct st2 {...},
  • 如果你修复你的结构声明,它仍然无法编译,你会得到一个错误,例如“错误:从类型‘struct st2’分配给类型‘struct st1’时类型不兼容”

标签: c linux struct variable-assignment assignment-operator


【解决方案1】:

这仅适用于两个结构具有相同类型的情况。否则你必须得到一个编译错误。

(如果你的编译器生成一个可执行文件,它可以做任何事情)。

【讨论】:

    【解决方案2】:

    这将导致错误,因为 st1 和 st2 是临时结构的对象。所以你最好试试这个... 您只需要在定义临时结构期间创建对象。

    # include <stdio.h>
    struct {
        int a;
        char b;
    }st1 = {0};
    
    struct {
        char c;
        int d;
    }st2 = {'A', 10};;
    
    int main()
    {
    //  struct st1 data1 = {0};
    //  struct st2 data2 = {'A',10};
    //  data1 = data2;
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      如果执行以下代码,data1的内容是什么?

      您的代码无法执行,因为它无法编译。 你会得到一个编译器错误,例如

      "error: incompatible types when assigning to type ‘struct st1’ from type ‘struct st2’" 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多