c进阶-结构体

目的:将不同类型的数据组合成一个有机整体
定义:
形式1

struct point{
    int x;
    int y;
};
struct point p1,p2;

形式2

struct point{
    int x;
    int y;
}p1,p2;

形式3

struct {
    int x;
    int y;
}p1,p2;

初始化:给结构体赋初值

#include<stdio.h>

int main() {
    struct point {
        int x;
        int y;
    }p2;

    struct point p1 = {1,3};
    p2.x = 2;
    p2.y = 4;
    struct point p3 = {5};

    printf("%d,%d\n", p1.x, p1.y);
    printf("%d,%d\n", p2.x, p2.y);
    printf("%d,%d", p3.x, p3.y);

    return 0;
}

结构与函数

函数接收、返回的是结构体的值

#include <stdio.h>

struct point {
    int x;
    int y;
};

struct point getstruct(void);//结构体作为函数的返回值
void output(struct point q);//结构体作为函数的接收值

int main(int argc, char **argv) {
    struct point y ={0,0};
    output(y);
    y=getstruct();
    output(y);
}

struct point getstruct(void){
    struct point p;
    scanf("%d",&p.x);
    scanf("%d",&p.y);
    return p;
}

void output(struct point q){
    printf("%d,%d",q.x,q.y);
}

指向结构的指针

If a large structure is to be passed to a function,it is generally more eficient to paa a pointer than to copy the whole structure.——K&R(p.131)
传递指针比传递结构更加高效

struct point *p= &p1;

p1.x=0;
(*p).x=0;
p->x=0;//p所指的x;这三种等价,用->表示指针所指的结构变量中的成员
#include <stdio.h>

struct point {
    int x;
    int y;
};

void getstruct(struct point *p); //结构体指针作为函数的接收值
void output(const struct point *q); //结构体指针作为函数的接收值

int main(int argc, char **argv) {
    struct point y = {0, 0};
    output(&y);
    getstruct(&y);
    output(&y);
    return 0;
}

void getstruct(struct point *p) {
    scanf("%d", &p->x); //p->x相当于(*p).x
    scanf("%d", &p->y); //相当于(*p).y
}

void output(const struct point *q) {
    printf("%d,%d", q->x, q->y);
}

数组与结构

数组结构
专卖店:单元的类型必须一致大商场:各成员类型可不同
a[0];用[] 下标访问单元today.day;用. 名字访问成员
变量本身a是指针变量本身不是指针
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值