用C语言指向Union的指针

待我称王封你为后i 2023-03-05 10:59 13阅读 0赞

联盟的指针 (Pointer to Union)

Pointer to union can be created just like other pointers to primitive data types.

可以创建指向联合的指针,就像指向原始数据类型的其他指针一样。

Consider the below union declaration:

考虑以下联合声明:

  1. union number{
  2. int a;
  3. int b;
  4. };

Here, a and b are the members of the union number.

这里, ab是联合的成员。

Union variable declaration:

联合变量声明:

  1. union number n;

Here, n is the variable to number.

在这里, nnumber的变量。

Pointer to union declaration and initialization:

联合声明和初始化的指针:

  1. union number *ptr = &n;

Here, ptr is the pointer to the union and it is assigning with the address of the union variable n.

在这里, ptr是指向并集的指针,并为其分配了并集变量n的地址。

Accessing union member using union to pointer:

使用联合指向指针访问联合成员:

  1. Syntax:
  2. pointer_name->member;
  3. Example:
  4. // to access members a and b using ptr
  5. ptr->a;
  6. ptr->b;

演示联合指针示例的C程序 (C program to demonstrate example of union to pointer)

  1. #include <stdio.h>
  2. int main()
  3. {
  4. // union declaration
  5. union number {
  6. int a;
  7. int b;
  8. };
  9. // union variable declaration
  10. union number n = { 10 }; // a will be assigned with 10
  11. // pointer to union
  12. union number* ptr = &n;
  13. printf("a = %d\n", ptr->a);
  14. // changing the value of a
  15. ptr->a = 20;
  16. printf("a = %d\n", ptr->a);
  17. // changing the value of b
  18. ptr->b = 30;
  19. printf("b = %d\n", ptr->b);
  20. return 0;
  21. }

Output:

输出:

  1. a = 10
  2. a = 20
  3. b = 30

翻译自: https://www.includehelp.com/c/pointer-to-union-in-c-language.aspx

发表评论

表情:
评论列表 (有 0 条评论,13人围观)

还没有评论,来说两句吧...

相关阅读