天天看点

用C语言指向Union的指针

联盟的指针 (Pointer to Union)

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

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

Consider the below union declaration:

考虑以下联合声明:

union number{
    int a;
    int b;
};
           

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

这里, a和b是联合号的成员。

Union variable declaration: 联合变量声明:
union number n;
           

Here, n is the variable to number.

在这里, n是number的变量。

Pointer to union declaration and initialization: 联合声明和初始化的指针:
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: 使用联合指向指针访问联合成员:
Syntax:
pointer_name->member;

Example:
// to access members a and b using ptr
ptr->a;
ptr->b;
           

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

#include <stdio.h>

int main()
{
    // union declaration
    union number {
        int a;
        int b;
    };

    // union variable declaration
    union number n = { 10 }; // a will be assigned with 10

    // pointer to union
    union number* ptr = &n;

    printf("a = %d\n", ptr->a);

    // changing the value of a
    ptr->a = 20;
    printf("a = %d\n", ptr->a);

    // changing the value of b
    ptr->b = 30;
    printf("b = %d\n", ptr->b);

    return 0;
}
           
Output: 输出:
a = 10
a = 20
b = 30
           
翻译自: https://www.includehelp.com/c/pointer-to-union-in-c-language.aspx

继续阅读