C语言---CONST指针,二级指针23/3/9

文章讲述了C语言中const关键字修饰指针的用法,强调了const指针不能修改指向的内存空间,而介绍的二级指针用于指向指针的指针,展示了如何使用二级指针进行排序操作。在示例中,const用于保护变量不被意外修改,而二级指针则用于动态数组或复杂数据结构的排序。
摘要由CSDN通过智能技术生成
//***************CONST指针**************

int main()
{
	int num = 233;
	int* pn = #
	*pn = 233333;//修改指向的内存空间的值
	pn = NULL;//修改指针的指向
	printf("%d %p\n", num, pn);

	const修饰的指针所指向的内存空间,不能通过指针去修改
	//const int* p1 = #

	//int x = 7;
	//p1 = &x;
	*p1 = 66;//error:左值指向const对象
	//printf("%d", *p1);//可以读取

	//int const* p1 = #
	*p = 66//
	//int x = 7;
	//p1 = &x;

	//const int* == int const* 

	int* const p1 = #
	*p1 = 66;//可以修改指向内存空间的数组
	int x = 6;
	// p1 = &x;//不能修改p1的指向
}

//******************二级指针指向指针的指针*********
int main()
{
	int age = 18;
	int* pa = &age;//pa存储的是普通变量

	printf("%p %p %p\n", pa, &pa,&age);

	//int pp = &pa;//warning C4047:int 和 int**不同
	int** pp = &pa;//定义一个二级指针
	//printf("%d", **pp);

	printf("%p, %p %d", pp, *pp, **pp);

	return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct {
	int number;
	char name[25];
	int chinese;
	int math;
	int english;
} Student;

int cmp(const void *p1,const void *p2)
{//二级指针
	Student** s1 = p1;
	Student** s2 = p2;

	int total1 = (*s1)->chinese + (*s2)->english + (*s2)->math;
	int total2 = (*s1)->chinese + (*s2)->english + (*s2)->math;

	if (total1 != total2)
	{
		return total2 - total1;
	}
	if ((*s1)->chinese != (*s2)->chinese)
	{
		return(*s2)->chinese - (*s1)->chinese;
	}
	if ((*s1)->math != (*s2)->math)
	{
		return(*s2)->math - (*s1)->math;
	}
	if ((*s1)->english != (*s2)->english)
	{
		return(*s2)->english - (*s1)->english;
	}
	return strcmp((*s1)->name, (*s2)->name);
}

void print_stu_info(Student* p)
{
	printf("%d %s %d %d %d\n",
		p->number,
		p->name,
		p->chinese,
		p->math,
		p->english);
}

int main()
{
	Student students[3];
	for (int i = 0; i < 3; i++)
	{
		scanf("%d%s %d%d%d",
			&students[i].number,
			students[i].name,
			&students[i].chinese,
			&students[i].english,
			&students[i].math);
	}
	Student* pstus[] = { students,students + 1,students + 2};

	printf("排序前:\n");
	for (int i = 0; i < 3; i++)
	{
		print_stu_info(pstus[i]);
	}
	//传入的其实是一个二级指针
	qsort(pstus, 3, sizeof(pstus[0]), cmp);

	printf("排序后:\n");
	for (int i = 0; i < 3; i++)
	{
		print_stu_info(pstus[i]);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值