c - C中的"Classes and initializers"

标签 c class pointers methods unions

#include <stdio.h>
  union test {
    int test1;
    int test2;
    int test3;
  };
  int testC(union test *x, int q, int w, int e) {
    (x->test3)=q;
        x--;
    (x->test2)=w;
        x--;
    (x->test1)=e;
        x--;
    return 0;
  };
  int main() {
    union test hi;
    testC(&hi,5,6,7);
    printf("%i, %i, %i \n", hi.test1, hi.test2, hi.test3);
        int x,*y = 0;
        x = 1;
        x++;
        scanf("%i\n", y);
  }

上面的代码应该创建一个 Union,然后将其所有组件“初始化”为输入,但它只是将自身初始化为第一个组件。我尝试过 x++ 并移动值,但似乎没有任何效果。

最佳答案

union 占用其最大成员所需的空间。这意味着它一次只能保存其中一名成员的值(value)。下面的答案很好地解释了这一点。

Difference between a Structure and a Union

关于c - C中的"Classes and initializers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50284158/

相关文章:

c# - 我怎样才能为 php 做 c# 字典呢?循环类

c - 指针增量与C中的索引增量相比如何

c - 是否可以查看一个和零的二进制文件?

c - fork: child 从哪里开始跑?

Java - 比较类?

C++ 重载 += 带有双指针的运算符

python - 简单继承的 Cython 编译错误 - 对象没有属性

c - 将 ctrl-z 发送到 C 中的串行端口(GSM SMS)

c - 如何一次性读取所有CPU核心的频率?

python - 使用装饰器向类添加方法