C语言结构体
C语言的结构(struct)是一种复杂的数据类型,可以包含多种数据类型,基本类型都能包含,但是不能包含函数,这是和C++中的结构不同的地方,但是可以包含函数指针,但是这也并不矛盾,因为本身指针指向的是一个地址,也是一个变量。
下面是结构的定义的示例:
struct Name
{
char *FirstNmae;
char *LastNmae;
};下面是声明一个结构变量,顺带着初始化了:
struct Name name1 = {"cy", "hu"};注意这里struct Name这是个整体,不能漏下前面的struct,这和C++里的结构体也是不一样的。当然可以使用 typedef 关键字来简化,如下:
typedef struct Point
{
int X;
int Y;
void (*printpoint)();
} Point;然后再使用就方便了:
Point point1 = {1, 2, testFunction};当然也可以定义结构体指针:
Point *p = &point1;
这里和数组等的不同,结构体变量的名字并不代表结构体的地址,所以还是要用上取地址符&,访问指向的结构体变量内容时,使用 ->运算符,如下:
printf("x = %d,y = %d
", p->X, p->Y);
p->printpoint();
完整的测试代码如下:
#include <stdio.h>
#include <stdlib.h>
void testFunction();
typedef struct Point
{
int X;
int Y;
void (*printpoint)();
} Point;
struct Name
{
char *FirstNmae;
char *LastNmae;
};
int main()
{
Point point1 = {1, 2, testFunction};
printf("x = %d,y = %d
", point1.X, point1.Y);
point1.printpoint();
Point *p = &point1;
printf("x = %d,y = %d
", p->X, p->Y);
p->printpoint();
struct Name name1 = {"cy", "hu"};
printf("Filst name:%s,Last name:%s", name1.FirstNmae, name1.LastNmae);
system("pause");
return 0;
}
void testFunction()
{
printf("This is a test function!
");
}

鲁公网安备 37148202000241号