写结构体指针前,先说一下 号和 -> 的区别

记得当初刚学C语言的时候,搞不清结构体的 . 号和 -> ,经常混淆二者的使用。

那么在C语言中 . 号是成员访问运算符,当我们需要访问结构的成员的时候,就会使用到它

而当我们需要使用结构体指针来访问结构成员的时候,就得使用->运算符了

结构体指针栗子:

​#include<stdio.h>
#include<string.h>
 
typedef struct student{
int id;
char name[10];
char sex;
}stu;   //结构体别名
 
void PrintStu(stu *student);
int main()
{
    //结构体对象
    stu stu1;
    printf("sizeof of stu1 is:%d\n",sizeof(stu1));
    stu1.id=2014;
    strcpy(stu1.name,"zhangfei");
    stu1.sex='m'; 
    PrintStu(&stu1); 
 
    printf("***************\n");
 
	//结构体指针
	stu *s = (stu*)malloc(sizeof(stu)); //申请堆内存
	s->id = 2018;
	strcpy(s->name, "zhangfei");
	s->sex = 'g';
	PrintStu(s);
 
    return 0;
}
void PrintStu(stu *student)
{
    printf("stu1 id is :%d\n",student->id);
    printf("stu1 name is :%s\n",student->name);
    printf("stu1 sex is :%c\n",student->sex);
 
}
 
​

结构体指针,就是指向结构体的指针。

解释C函数中的形参:

void PrintStu(stu *student)中的形参stu *student,说通俗点就是用来接住外部传来的地址&stu1。

即 stu *student=&stu1; student可以取其他名字,形参并不是固定的。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。