易百教程

结构体成员

要访问结构体(struct)的成员,请使用点表示法。假设有以下定义。

struct Dog
{
  int age;
  int height;
  char name[20];
  char father[20];
  char mother[20];
};

struct Dog d1 = {4, 7,"A", "B", "C"};

可以访问年龄成员:

d1.age = 12;

可以在初始化列表中指定成员名称,如下所示:

d1 = {.height = 15, 
      .age = 30,
      .name = "A", 
      .mother = "B", 
      .father = "C"
};

示例代码

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>

typedef struct Dog Dog;            // 将Dog定义为类型名称

struct Dog                         // 结构类型定义
{
    int age;
    int height;
    char name[20];
    char father[20];
    char mother[20];
};

int main(void)
{
    Dog my_dog; // 结构变量声明

    // 从输入数据初始化结构变量
    printf_s("Enter the name of the dog: ");
    scanf_s("%s", my_dog.name, sizeof(my_dog.name));     // Read the name

    printf_s("How old is %s? ", my_dog.name);
    scanf_s("%d", &my_dog.age);                           // Read the age

    printf_s("How high is %s ( in hands )? ", my_dog.name);
    scanf_s("%d", &my_dog.height);                        // Read the height

    printf_s("Who is %s's father? ", my_dog.name);
    scanf_s("%s", my_dog.father, sizeof(my_dog.father)); // Get pa's name

    printf_s("Who is %s's mother? ", my_dog.name);
    scanf_s("%s", my_dog.mother, sizeof(my_dog.mother)); // Get ma's name

    // 打印输出结果:
    printf_s("%s is %d years old, %d hands high,",
        my_dog.name, my_dog.age, my_dog.height);
    printf_s(" and has %s and %s as parents.\n", my_dog.father, my_dog.mother);
    system("pause");
    return 0;
}

执行上面示例代码,得到以下结果:

Enter the name of the dog: 小pp
How old is 小pp? 2
How high is 小pp ( in hands )? 3.4
Who is 小pp's father? Who is 小pp's mother? FP MP
小pp is 2 years old, 3 hands high, and has .4 and FP as parents.