[TwistedFate]高级指针

本文深入探讨了C语言中结构体与指针的基本概念及应用实践,包括结构体成员变量的操作、结构体指针的使用、通过指针访问结构体成员的方法等,并通过具体实例展示了如何利用结构体和指针解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:
1.创建一个学生类
2.声明一个结构体 成员变量:名字 性别 年龄 分数

typedef struct student{
    char name[20];
    char sex;
    int age;
    float score;
    }Student;

1.结构体指针:指向结构体的指针

 Student stu1 = {"zed",'m',28,98.0};
 Student *p = &stu1;
 printf("%s\n",stu1.name);
 // (*p).name
 // *p取出指针所指向的空间保存的值
 printf("%s\n",(*p).name);
 // 结构体指针当中 经常使用->指向符
 printf("%s\n",p->name);    
需求:编写函数 打印所有的成员变量
void printStudent(Student *stu)
{
    printf("%s %c %d %.2f",stu->name, stu->sex, sti->age, stu->score);
}
`printStudent(p);`
printf("%p\n",p);
printf("%p\n",&stu1);
printf("%p\n",p->name);
// 结构体指针指向结构变量 相当于指向结构变量的第一个成员变量

// 练习1:定义一个点结构体,编写函数利用指针打印两点间的距离

typedef struct CPoint{
    float x;
    float y;
    }CPoint; 
void printDis(CPoint *point1, CPoint *point2)
{
    float a = point1->x - point2->x;
    float b = point1->y - point2->y;
    float dis = sqrtf(a * a + b * b);
    printf("Distance = %.2f",dis);
}
 CPoint m = {3.0, 4.0};
 CPoint n = {6.0, 8.0};
 CPoint *p1 = &m;
 CPoint *p2 = &n;
 printDis(p1,p2);

// 练习2:编写一个函数,将学生名字首字母大写,空格改成下划线

void alterName(Student *stu)
{
    int i = 0;
    while(stu->name[i] != 0){
        if(stu->name[i] ==' ')
            stu->name[i] = ' ';
        i++;
    }
    stu->name[0] = p->name[0] + 'A' - 'a';
    printStudent(stu);
}
Student stu2 = {"c  bb ar", 'm', 15, 88.0};
Student *p = &stu2;
alterName(p);

// 声明三个结构体变量

Student stu3 = {"king", 'm', 60, 120.0};
Student stu4 = {"mx", 'm', 23, 50.0};
Student stu5 = {"tt", 'm', 54, 90.0};
Student *p = &stu3;
printf("%p\n",p);
// 结构体指针 地址+1 相当于加了整个结构体的字节数
printf("%p\n",p + 1);
// 声明一个结构体数组保存三个学生
Student stus[3] = {stu3, stu4, stu5};
Stundet *p = stus;
printf("%p\n",p);
// 结构体指针 指向结构体数组 就相当于 指向结构体数组的首元素
printrf("%p\n",&stus[0]);
// 如何利用指针 取出数组中的元素*(p + 1)
// (*(p + 1)).name
printf("%s\n",(*(p + 1)).name);
printf("%s\n"),(p + 1)->name);

// 练习3:编写函数 利用指针打印 结构体数组所有元素

void printStudentArray(Stundet *stus, int count)
{
    for(int i = 0; i < count; i++)
    {
        printStudent(stus + i);
    }
}

2.预编译指令
宏定义:
1.预编译时进行替换(编译前)
2.替换的过程
带参数宏定义: 参数使用什么名字 后面使用参 数的时候名字要一致
命名规范:
1.以小写k开头 后面驼峰 编写宏定义
2.全部大写
一般宏定义的参数 都已大写来写
#define kMaxValue(A,B) ((A) > (B) ? (A) : (B))
// 加括号是为了防⽌受操作符优先级的影响
条件编译:
作⽤:按不同的条件,编译不同的代码。
条件编译 有三种形式。
(1)

#ifdef WL
printf("WL已经定义了");
#else
#endif

(2)

#ifndef
#else
#endif

// 作用与第一种相反
(3)

#if(常量表达式)
代码段1
#else
代码段2
#endif

// 如果 常量表达式结果⾮0 编译器编译代码段1,否则编译代码段2。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值