您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
055第十章 结构体与共用体03(新版)
发布时间:2021-05-06 21:13:01编辑:雪饮阅读()
结构体与指针的一些区别与联系
首先在结构体内部成员,这里以char类型为例,若定义一个字符串一般有两种形式。
一种通过字符数组形式,一种通过指针形式。
那么对于字符数组形式,要对其字符串进行整体重新赋值是不可能的,必须对每个字符进行赋值,这不仅仅是在结构体,就算是基类中也是如此。
另外一方面,对于结构体本身来说,若某个变量是结构体的实例,且不是指针的情况下,则访问其成员需要以”.”形式访问,而若是指针,则需要以”->”来访问。
具体可以看下如下两个实例。
实例1:
#include <stdio.h>
#include <string.h>
struct student
{
int num;
char *name;
float score[3];
};
void print( struct student stu )
{ //这里stu是接收的student结构体的栈实例(非指针)所以这里访问其成员时候需要用"."来连接
printf("\tnum : %d\n", stu.num);
printf("\tname : %s\n", stu.name);
printf("\tscore_1 : %5.2f\n", stu.score[0]);
printf("\tscore_2 : %5.2f\n", stu.score[1]);
printf("\tscore_3 : %5.2f\n", stu.score[2]);
printf("\n");
}
void main()
{
struct student stu;
stu.num = 8;
//这里stu.name是通过指针定义的,所以字符串赋值可以一次性赋值
stu.name = "xkws.com!";
stu.score[0] = 98.5;
stu.score[1] = 99.0;
stu.score[2] = 99.5;
print( stu );
}
编译并运行
D:\cproject>gcc main.c -o m
D:\cproject>m.exe
num : 8
name : xkws.com!
score_1 : 98.50
score_2 : 99.00
score_3 : 99.50
实例2:
#include <stdio.h>
#include <string.h>
struct student
{
int num;
char name[20];
float score[3];
};
void print( struct student *p )
{
/*
这里p是接收来自student的实例(指针形式),指針形式不能用“.”的形式訪問成員,必須用“->”訪問
*/
printf("\tnum : %d\n", p->num);
printf("\tname : %s\n", p -> name);
printf("\tscore_1 : %5.2f\n", p -> score[0]);
printf("\tscore_2 : %5.2f\n", p -> score[1]);
printf("\tscore_3 : %5.2f\n", p -> score[2]);
printf("\n");
}
void main()
{
struct student stu;
stu.num = 8;
//由于这里stu.name是通过字符数组定义的,所以字符串赋值要通过专门的字符串拷贝函数strcpy来实现
strcpy(stu.name, "xkws.com!");
stu.score[0] = 98.5;
stu.score[1] = 99.0;
stu.score[2] = 99.5;
print( &stu );
}
编译并运行
关键字词:结构体,指针,字符