c语言(11)—指针(2)数组和字符串的传递

一、指针和数组的关系

1.数组和指针的关系

数组的数组名是指向数组第一个元素的指针常量

数组的数组名a可以理解为int *型(两种特殊情况不能理解为int*型)

sizeof:sizeof(a) == 20 sizeof(int *) == 8

&: &a == int (*)[5] &int * == int **

2. 数组的本质:

int a[5];

开辟20个字节空间,常量a表示空间首地址

当访问a[i]元素时,等价于 *(a+i),能操作对应的空间

3. 数组作为函数参数

传递形式:

int fun(int *parray, int len);

e.g.封装一个函数inputArray从终端接收数组元素到数组中
封装一个函数sortArray实现对数组的排序
封装一个函数outputArray实现对数组的打印

思路:在主函数中定义一个数组,并取地址使传入三个被调函数,在第一个被调函数中接收数组地址,注意接收使需要取地址;在第二个被调函数中用冒泡排序对数组进行排序;在第三个被调函数中用for循环打印排序后的数组

#include <stdio.h>

int inputArray(int *parray, int len)
{
	int i = 0;

	for (i = 0; i < len; i++)
	{
//		scanf("%d", &parray[i]);
		scanf("%d", parray+i);
	}

	return 0;
}

int sortArray(int *parray, int len)
{
	int j = 0;
	int i = 0;
	int tmp = 0;

	for (j = 0; j < len-1; j++)
	{
		for (i = 0; i < len-1-j; i++)
		{
			if (parray[i] > parray[i+1])
			{
				tmp = parray[i];
				parray[i] = parray[i+1];
				parray[i+1] = tmp;
			}
		}
	}

	return 0;
}

int outputArray(int *parray, int len)
{
	int i = 0;

	for (i = 0; i < len; i++)
	{
		printf("%d ", parray[i]);
	}
	printf("\n");

	return 0;
}

int main(void)
{
	int a[5] = {0};

	inputArray(a, 5);
	sortArray(a, 5);
	outputArray(a, 5);

	return 0;
}

4.  字符型数组及字符串的传递

(1)字符串传参

        int fun(char *pstr);

(2)字符串的遍历

while (*pstr != '\0')
{
pstr++;
}

二、const指针

1. const指针形式:

(1)const int *p;

         int const *p;

这两种形式等价(const修饰*p),指针变量p的值(指向)可以改变,但是不能利用p修改指向空间中的值

const char *p = "hello word";

p = "thank you";  对,可以改变p指向

strcpy(p, "thank you");  错,不能改变p指向空间的值

(2)int *const p;

这种形式(const修饰p)指针变量p的值不能变,但可以利用指针p修改指向空间中的值,注意一定要记得初始化

char str[] = "hello world";

str = "thank you" ;错 ,str指向唯一不能改变

strcpy(str, "thank you");  对,可以改变str指向空间的值

(3)const int *const p;
         int const *const p;

这两种形式等价,指针变量p的值不能变,也不能通过p修改指向空间中的值

三、指针函数

指针函数是函数,函数的返回值是指针

注:不能返回局部变量的地址,因为函数结束后会被回收;指针函数返回的地址可以作为下一个函数调用的参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值