以前学习c的笔记:
一:理论
typedef是类型定义的意思。
typedef struct 是为了使用这个结构体方便。
具体区别在于:
若struct node{ }这样来定义结构体的话。在定义 node 的结构体变量时,需要这样写:struct node n;
若用typedef,可以这样写:typedef struct node{}NODE; 。在申请变量时就可以这样写:NODE n;其实就相当于 NODE 是node 的别名。区别就在于使用时,是否可以省去struct这个关键字。
首先:
在C中定义一个结构体类型时如果要用typedef:
typedef struct Student
{
int no;
char name[12];
}Stu,student;
于是在声明变量的时候就可:Stu stu1;或者:student stu2;(Stu 和student 同时为Student的别名)
如果没有typedef即:
struct Student
{
int no;
char name[12];
}Stu;
就必须用struct Student stu1;或者struct Stu stu1;来声明
另外这里也可以不写Student(于是也不能struct Student stu1;了)
typedef struct
{
int no;
char name[12];
}Stu;
//stu2是一个结构体类型,即stu2是Student2的别名
使用时可以直接访问stu1.no
但是stu2则必须先定义 stu2 s2;
然后 s2.no=10;
二:实践
//main函数文件
#include <stdio.h>
#include "tool.h"
int main(int argc,char * argv[])
{
helloData2.intData2 = 1;
helloData2.intHelloCount2 = 2;
helloData hello ;
hello.intHelloCount = 1 ;
hello.intData = 2 ;
helloData hello7 =
{
.intHelloCount = 1 ,
.intData = 2 ,
} ;
struct helloData2_S hello2;
hello2.intHelloCount2 = 1 ;
hello2.intData2 = 2 ;
struct student_st s2 =
{
.name = "YunYun",
.c = 'B',
.score = 92,
};
show_student(&s2);
struct student_st stus[2] =
{
{
.name = "YUN2",
.c = 'D',
.score = 94,
},
{
.name = "YUN3",
.c = 'E',
.score = 100,
.name = "Xxx"
},
};
show_student(&stus[1]);
//show_student(&stus[2]); //调用&stus[2]的地址会出错
int intData;
intData = 456;
int arr[] = {1,2,3,4,20};
int ret =tool(arr ,5);
printf("%d \n", intData);
printf("%d \n", ret );
printf("%d \n", hello.intHelloCount);
return 0;
}
//tool.c文件
#include <stdio.h>
#include "tool.h"
int tool(int arr[],int n)
{
int m = arr[0];
int i;
for(i=0; i<n; i++)
{
if(arr[i] > m)
{
m=arr[i];
}
}
return m;
}
void show_student(struct student_st *stu)
{
printf("c = %c, score = %d, name = %s\n", stu->c, stu->score, stu->name);
}
//tool.h 文件
#ifndef _TOOL_H
#define _TOOL_H
#include <stdio.h>
typedef struct helloData_S
{
int intHelloCount ;
int intData;
} helloData;
struct helloData2_S
{
int intHelloCount2 ;
int intData2;
} helloData2 ;
struct student_st
{
char c;
int score;
const char *name;
};
int tool(int arr[],int n) ;
void show_student(struct student_st *stu);
#endif
makefile 文件
CC = gcc #编译器的型号
.PHONY: all #伪所址
all: hello.c tool.o
$(CC) hello.c tool.o -o all
tool.o:tool.c
$(CC) -c tool.c
clean:
rm *.o all
结果: