上述代码不用指针怎么写?
时间: 2023-06-12 11:04:13 浏览: 44
可以使用数组来代替指针。
以下是使用数组实现的示例代码:
```c++
#include <iostream>
using namespace std;
int main() {
const int SIZE = 5;
int arr[SIZE] = {1, 2, 3, 4, 5};
// 输出数组中的元素
for (int i = 0; i < SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;
// 修改数组中的元素
for (int i = 0; i < SIZE; i++) {
arr[i] *= 2;
}
// 再次输出数组中的元素
for (int i = 0; i < SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
1 2 3 4 5
2 4 6 8 10
```
相关问题
把上述代码用指针形式实现
下面是使用指针形式实现的代码:
```c++
#include <iostream>
using namespace std;
void move(int *p, int m, int n);
int main()
{
int m, n;
cout << "请输入数据个数m及左移的位数n:";
cin >> m >> n;
// 产生斐波那契数列前m项的值
int *a = new int[m];
int *p = a;
*p = 0;
p++;
*p = 1;
for (int i = 2; i < m; i++) {
*(p+i) = *(p+i-1) + *(p+i-2);
}
// 输出原始数组
cout << "原始数组为:";
for (int i = 0; i < m; i++) {
cout << *(p+i) << " ";
}
cout << endl;
// 对数组a进行左移n位
move(p, m, n);
// 输出移动后的数组
cout << "移动后的数组为:";
for (int i = 0; i < m; i++) {
cout << *(p+i) << " ";
}
cout << endl;
delete[] a;
return 0;
}
void move(int *p, int m, int n)
{
n = n % m; // 确保n小于m
int *temp = new int[n]; // 定义一个临时数组,用于存储前n个元素
for (int i = 0; i < n; i++) {
*(temp+i) = *(p+i);
}
for (int i = 0; i < m-n; i++) {
*(p+i) = *(p+i+n);
}
for (int i = 0; i < n; i++) {
*(p+m-n+i) = *(temp+i);
}
delete[] temp;
}
```
运行结果与前面的代码一致。
将上述代码优化运用指针
好的,以下是使用指针进行优化的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int arr[5] = {5, 3, 1, 4, 2};
int *ptr = arr; // 将指针 ptr 指向数组 arr 的首地址
// 使用指针遍历数组并输出元素
for (int i = 0; i < 5; i++) {
cout << *(ptr + i) << " "; // 输出指针指向的元素
}
return 0;
}
```
在优化后的代码中,我们使用指针 `ptr` 指向数组 `arr` 的首地址,然后在遍历数组时使用指针来访问数组元素。具体来说,我们通过 `*(ptr + i)` 来访问数组中第 `i` 个元素。这样可以减少对数组名的使用,从而使代码更加简洁。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)