C语言中的结构变量(Structure Variable)以及Struct、Typedef的用法

关键字:Struct、Typedef

运算符:.   (成员运算符)

一、初步了解结构体

有人说:程序 = 算法+数据结构

程序设计中最重要的一个步骤就是选择一个表示数据的好方法。在多数情况下使用简单的变量或数组是远远不够的。C使用结构变量进一步增强了表示数据的能力。

关键字 Struct 用于建立结构声明(structure declaration),结构声明是用来描述结构如何组合的主要方法。它把一些我们常用的数据类型组合到一起形成我们需要的结构

struct book{/*book是一个模板或者标记*/
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
};

二、结构变量的几种声明方法

2.1 有标记的结构变量声明

struct book library; /*book是我们定义的结构的标记,library是我们声明的变量名*/

实际上这种声明是以下声明方法的简化:

struct book{
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
}library;/*在定义之后跟变量名*

2.2 不带标记的结构变量声明(实际上是将声明和定义结构变量合成到一步中)

struct{/*无标记*/
	char title[MAXTITL];
	char author[MAXAUTL];
	float value;
} library;

2.3 使用 typedef 进行变量声明(用于多次使用定义的结构体)

typedef 是一种高级数据特性,它能够为某一类型创建自己的名字。在这方面它与 #define 相似,但是,不同的是 #define 是对值创建名称,而 typedef 是对类型创建名称。

基本用法:

typedef unsigned char BYTE;
/*随后就可以用BYTE定义数据了,例如:*/
BYTE x,y[10],*z;

该定义的作用域:若定义在函数内部,作用域为局部。若定义在函数外部,则为全局作用域

所以,定义结构体时也有两种方法:

typedef struct complex{
	float real;
	float imag;
}COMPLEX
/*第一种方法带有结构的标记*/
/*可以用COMPLEX代替 struct complex来表示复数*/

typedef struct {double x; double y;} rect;
/*第二种方法省略了结构的标记*/
/*用rect代替struct{double x; double y;}*/

三、下面是C的一段代码(使用结构体定义了book的数据类型):

#include<stdio.h>
#define MAXTITL 41
#define MAXAUTL 31
struct book{
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
};

int main(void)
{
    struct book library;
    printf("Please enter the book title.\n");
    gets(library.title);
    printf("Now enter the author.\n");
    gets(library.author);
    printf("Now enter the value.\n");
    scanf("%f",&library.value);
    printf("%s by %s: $%.2f\n",library.title,library.author,library.value);

    return 0;
}

运行结果:

定义结构体时我们可以对其进行下面两种操作:

3.1 访问结构成员

使用成员操作符“.”,比如 library.title、library.author、library.value

3.2 初始化结构体

对于普通的数据类型,比如一个数组,我们是如何对其进行初始化的?

int shuzu[7] = {0,1,2,3,4,5,6}

我们定义的结构体同样可以用这种方式初始化:

struct book library = {
	"C_struct",
	"Linden",
	23
};

也可以按照任意的顺序使用指定初始化项目:

struct book library = {
	.title = "C_struct",
	.author = "Linden",
	.value = 23
};


PS:因为最近在学习python,所以用python中的类实现了一下上面的结构

class Library:
	def __init__(self,title,author,value):
		self.title = title
		self.author = author
		self.value = value

def main():
	book_title = input("Please enter the book title.\n")
	book_author = input("Now enter the author.\n")
	book_value =  float(input("Now enter the value.\n"))
	book = Library(book_title,book_author,book_value)
	print("%s by %s: $%.2f"%(book.title,book.author,book.value))
	
main()

#运行结果如下
Please enter the book title.
Python_struct
Now enter the author.
Linden
Now enter the value.
23
Python_struct by Linden: $23.00
 

猜你喜欢

转载自blog.csdn.net/sinat_38486449/article/details/80020262