C语言结构体指针的示例分析

这篇文章给大家分享的是有关C语言结构体指针的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

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

记得当初刚学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可以取其他名字,形参并不是固定的。

感谢各位的阅读!关于“C语言结构体指针的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!