学点 C 语言(24): 数据类型 - 结构(struct)

180it 2020-03-05 AM 1663℃ 0条

学点 C 语言(24): 数据类型 - 结构(struct)

  1. 结构就是多个变量的集合:

    include <stdio.h>

int main(void)
{

struct Rec {
    int x;
    int y;
};

struct Rec r1;

r1.x = 111;
r1.y = 222;

printf("%d, %d", r1.x, r1.y);

getchar();
return 0;

}

  1. 定义时同时声明变量:

    include <stdio.h>

int main(void)
{

struct Rec {
    int x,y;
} r1,r2;

r1.x = 111;
r1.y = 222;

r2.x = 333;
r2.y = 444;

printf("%d, %d\n", r1.x, r1.y);
printf("%d, %d\n", r2.x, r2.y);

getchar();
return 0;

}

  1. 定义时同时声明变量并赋值:

    include <stdio.h>

int main(void)
{

struct Rec {
    int x,y;
} r1 = {777,888};

printf("%d, %d\n", r1.x, r1.y);

getchar();
return 0;

}

include <stdio.h>

int main(void)
{

struct Rec {
    char  name[12];
    short age;
} r1 = {"ZhangSan", 12};

printf("%s, %u", r1.name, r1.age);

getchar();
return 0;

}

  1. 声明变量是赋初值:

    include <stdio.h>

int main(void)
{

struct Rec {
    char  name[12];
    short age;
};

struct Rec r1 = {"ZhangSan", 12};

printf("%s, %u", r1.name, r1.age);

getchar();
return 0;

}

  1. 声明后给字符串赋值有点麻烦:

    include <stdio.h>

    include <string.h>

int main(void)
{

struct Rec {
    char  name[12];
    short age;
};

struct Rec r1;

strcpy(r1.name, "ZhangSan");
r1.age  = 18;

printf("%s, %u", r1.name, r1.age);

getchar();
return 0;

}

  1. 如果在定义时直接声明变量, 可省略结构名:

    include <stdio.h>

int main(void)
{

struct {
    char  name[12];
    short age;
} r1 = {"ZhangSan", 12};

printf("%s, %u", r1.name, r1.age);

getchar();
return 0;

}

  1. 通过 scanf 赋值:

    include <stdio.h>

int main(void)
{

struct Rec {
    char  name[12];
    short age;
} r1;

printf("name: ");
scanf("%s", r1.name);

printf("age: ");
scanf("%d", &r1.age);

printf("Name: %s; Age: %d", r1.name, r1.age);

getchar(); getchar();
return 0;

}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

学点 C 语言(24): 数据类型 - 结构(struct)