(C语言)指针作为函数参数的传递、typedef的作用

1、结构体前面加不加typedef有什么区别?

typedef struct BiTNode{
    char data;
    struct BiTree *lchild, *rchild;
    int numl,numr;
}BiTNode,*BiTree;

结构体名没有加typedef的话,以后每次定义变量都必须是这样的:
struct BiTNode * p ;

struct BiTree root = (struct BiTree)malloc(sizeof(struct BiTNode));

而如果加了typedef,那么之后的定义新变量课直接用结构名定义:
BiTree *p;

BiTree p = (BiTree)malloc(sizeof(BiTNode));

好处就是代码更加简洁且直观。

补充
我发现typedef 好像没那么简单。

struct studentInfo{
	char name[10];
	char number[10];
	int score;
}stu[100];

首先来看下上面这个代码:是一个结构体数组,这里的stu[100] 是指该结构体的变量,之后我们可以直接给这个变量赋值。那假如加上typedef 呢?

typedef struct studentInfo{
	char name[10];
	char number[10];
	int score;
}stu[100];

加上typedef 会报错。因为这里的stu[100]默认为studentInfo 取了一个别名,但stu[100] 和studentInfo 类型不同,肯定会报错。那我们重新定义一个变量

stu s;//这里的s就是一个大小为100 的结构体数组。

2、指针作为函数参数的传递

2.1值传递
#include <stdio.h>

void swap1(int x,int y){
	int t;
	t=x;
	x=y;
	y=t;
}
int main()
{
	int a=1,b=2;
	swap1(a,b);	printf("s1:a=%d,b=%d\n",a,b);
	return 0;
}

在这里插入图片描述

2.2地址传递

1

void swap2(int *px,int *py){
	int t;
	t=*px;
	*px=*py;
	*py=t;
}
int main()
{
	int a=1,b=2;
	int *pa=&a,*pb=&b;
	swap2(pa,pb);
	printf("s2:a=%d,b=%d\n",a,b);
 	return 0;
}

在这里插入图片描述
2、本质上还是值传递,指针变量本质上也是一个无符号类型变量。(看我画的图可以明白其过程)

void swap3(int *px,int *py){
	int *t;
	t=px;
	px=py;
	py=t;
}
int main()
{
	int a=1,b=2;
	int *pa=&a,*pb=&b;
	swap3(pa,pb);
	printf("s3:a=%d,b=%d\n",a,b);
 	return 0;
}

在这里插入图片描述
上面三种情况的结果如下:
在这里插入图片描述

2.3二级指针的传递
#include <stdio.h>

void swap(int **x, int **y)
{
    int t;

    t = **x;
    **x = **y;
    **y = t;
}
int main()
{
    int a = 10, b = 20;
    int *pa = &a;
    int *pb = &b;

    swap(&pa, &pb);
    printf("a = %d\nb = %d", a, b);

    return 0;
}

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

要是以后再混乱,就回来翻一翻。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值