指针在函数参数传递、数组操作及字符串处理中的应用
立即解锁
发布时间: 2025-08-19 01:36:33 阅读量: 1 订阅数: 6 


C++面向对象编程入门与实践
# 指针在函数参数传递、数组操作及字符串处理中的应用
## 1. 指针与引用作为函数参数的比较
在函数参数传递方面,传递指针和传递引用有相似之处,它们都允许函数修改调用程序中的变量,但机制不同。引用是原始变量的别名,而指针是变量的地址。
## 2. 数组作为函数参数的传递
### 2.1 指针表示法与数组表示法
在将数组作为参数传递给函数时,使用指针表示法比数组表示法更为常见。以下是 `PASSARR` 程序示例:
```cpp
// passarr.cpp
// array passed by pointer
#include <iostream>
using namespace std;
const int MAX = 5; //number of array elements
int main()
{
void centimize(double*); //prototype
double varray[MAX] = { 10.0, 43.1, 95.9, 59.7, 87.3 };
centimize(varray); //change elements of varray to cm
for(int j=0; j<MAX; j++) //display new array values
cout << "varray[" << j << "]="
<< varray[j] << " centimeters" << endl;
return 0;
}
//--------------------------------------------------------------
void centimize(double* ptrd)
{
for(int j=0; j<MAX; j++)
*ptrd++ *= 2.54; //ptrd points to elements of varray
}
```
函数原型中,`double*` 等同于 `double[]`,但指针语法更常用。由于数组名就是数组的地址,调用函数时无需使用取地址运算符 `&`。在 `centimize()` 函数中,数组地址被存储在 `ptrd` 变量中,通过递增 `ptrd` 来依次访问数组元素。
### 2.2 运算符优先级和结合性
对于表达式 `*ptrd++`,我们需要明确它是递增指针还是指针所指向的内容。`*`(作为解引用运算符)和 `++` 具有相同的优先级,但它们通过结合性来区分。一元运算符如 `*` 和 `++` 具有右结合性,因此表达式被解释为 `*(ptrd++)`,即先递增指针,再对结果地址应用解引用运算符。
## 3. 数组元素排序
### 3.1 使用指针排序的基础程序
`PTRORDER` 程序使用指针来对两个数进行排序,若第二个数小于第一个数,则交换它们。以下是代码示例:
```cpp
// ptrorder.cpp
// orders two arguments using pointers
#include <iostream>
using namespace std;
int main()
{
void order(int*, int*); //prototype
int n1=99, n2=11; //one pair ordered, one not
int n3=22, n4=88;
order(&n1, &n2); //order each pair of numbers
order(&n3, &n4);
cout << "n1=" << n1 << endl; //print out all numbers
cout << "n2=" << n2 << endl;
cout << "n3=" << n3 << endl;
cout << "n4=" << n4 << endl;
return 0;
}
//--------------------------------------------------------------
void order(int* numb1, int* numb2) //orders two numbers
{
if(*numb1 > *numb2) //if 1st larger than 2nd,
{
int temp = *numb1; //swap them
*numb1 = *numb2;
*numb2 = temp;
}
}
```
### 3.2 冒泡排序示例
`PTRSORT` 程序使用 `PTRORDER` 中的 `order()` 函数对整数数组进行排序,采用冒泡排序算法。以下是代码示例:
```cpp
// ptrsort.cpp
// sorts an array using pointers
#include <iostream>
using namespace std;
int main()
{
void bsort(int*, int); //prototype
const int N = 10; //array size
//test array
int arr[N] = { 37, 84, 62, 91, 11, 65, 57, 28, 19, 49 };
bsort(arr, N); //sort the array
for(int j=0; j<N; j++) //print out sorted array
cout << arr[j] << " ";
cout << endl;
return 0;
}
//--------------------------------------------------------------
void bsort(int* ptr, int n)
{
void order(int*, int*); //prototype
int j, k; //indexes to array
for(j=0; j<n-1; j++) //outer loop
for(k=j+1; k<n; k++) //inner loop starts at outer
order(ptr+j, ptr+k); //order the pointer contents
}
//--------------------------------------------------------------
void order(int* numb1, int* numb2) //orders two numbers
{
if(*numb1 > *numb2) //
```
0
0
复制全文
相关推荐










