当前位置:天才代写 > tutorial > C语言/C++ 教程 > 学点C语言(24):数据范例 – 布局(struct)

学点C语言(24):数据范例 – 布局(struct)

2017-11-03 08:00 星期五 所属: C语言/C++ 教程 浏览:426

副标题#e#

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;
}

2. 界说时同时声明变量:

#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;
}

3. 界说时同时声明变量并赋值:

#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;
}


#p#副标题#e#

4. 声明变量是赋初值:

#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;
}

5. 声明后给字符串赋值有点贫苦:

#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;
}

6. 假如在界说时直接声明变量, 可省略布局名:

#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;
}

7. 通过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;
}

返回“学点C语言 – 目次”

 

    关键字:

天才代写-代写联系方式