//利用指针交换两数的值
#include<iostream>
using namespace std;
void swap(int *m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
int main()
{
int a = 10;
int b = 20;
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
int *p = &a;
int *q = &b;
int temp;
temp = *p;
*p = *q;
*q = temp;
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
int c = 100;
int d = 200;
cout<<"c = "<<c<<" "<<"d = "<<d<<endl;
swap(&c, &d);
cout<<"c = "<<c<<" "<<"d = "<<d<<endl;
return 0;
}

一、指针作为函数参数
1、 数组作为函数参数可以退化为指针
2、传递数组时需要加上数组的大小 ,字符数组除外
3、除了字符数组外没法在函数体内通过指针求出数组大小,因为不知道越界之后是什么值
#include<iostream>
#include<string.h>
using namespace std;
//传递数组时需要加上数组的大小 ,字符数组除外
//除了字符数组外没法在函数体内通过指针求出数组大小,因为不知道越界之后是什么值
void print1(int *arr, int len) //void print(int arr[], int len)
{
for(int i=0; i<len; i++)
{
cout<<arr[i]<<endl;
}
}
//对于字符数组,有两种方法求出字符串长度
void print2(char *arr)
{
//int len = strlen(arr);
int len = 0;
while(arr[len] != '\0')
{
len++;
}
for(int i=0; i<len; i++)
{
cout<<arr[i]<<endl;
}
}
int main()
{
int arr1[] = {0,1,2,3,4,5,6,7,8,9};
int len = sizeof(arr1)/sizeof(arr1[0]);
print1(arr1, len);
char arr2[] = "hello world";
print2(arr2);
}

二、函数的返回值是指针
#include<iostream>
using namespace std;
//返回值是 char * 类型
char * test()
{
//字符数组 创建位置在栈区 这种写法不可以
//char arr[] = "hello world";
//字符串常量 会在程序运行时 常量区 地址未被销毁 只能读 在程序结束时销毁
char *arr = "hello world";
return arr;
}
int main()
{
//用函数对应的类型的指针接受返回值
char *p = test();
cout<<p<<endl;
}

131




被折叠的 条评论
为什么被折叠?



