结构体定义 struct 用法详解和用法小结(记录)

以前学习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

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七 六 伍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值