使用指针传递数组地址实现动态内存分配
要通过指针传递'temp'数组的地址,您可以将函数'fib'的参数类型更改为'int**',并在函数内部使用间接赋值操作来修改指针的值。这样,指针就可以指向'temp'数组了。
以下是修改后的代码:
#include <iostream>
#include <stdio.h>
using namespace std;
void arrge(int* arr, int n) {
int i, j, a;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
a = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = a;
}
}
}
}
void fib(int arr[], int n, int** temp) {
int a[100] = { 0 };
int b[100] = { 0 };
int i, j = 0;
for (i = 0; i < n; i++) {
if (arr[i] % 2 != 0) {
a[j] = arr[i];
j++;
}
}
int u = 0;
for (i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
b[u] = arr[i];
u++;
}
}
arrge(b, u);
arrge(a, j);
int m = 0;
for (i = 0; i < j + u; i++) {
if (i < j) {
(*temp)[i] = a[i];
}
else if (i >= j && i < j + u) {
(*temp)[i] = b[m];
m++;
}
}
}
int main() {
int n, num;
int i;
int arr[100] = { 0 };
for (n = 0;; n++) {
cin >> num;
if (num == 0) {
break;
}
arr[n] = num;
}
int temp[100] = { 0 };
int* p = temp;
fib(arr, n, &p);
for (i = 0; i < n; i++) {
cout << *p << " ";
p++;
}
return 0;
}
现在,我们将'temp'数组的地址传递给'fib'函数,并在函数中使用间接赋值操作'*temp'来修改数组的值。在'main'函数中,我们声明了一个名为'temp'的整数数组,并将其地址传递给'fib'函数。然后,在打印数组时,我们通过递增指针'p'来访问数组的元素。
这样,'temp'数组将在整个程序执行期间存在,并且可以正确地输出结果。
希望对您有所帮助!如果还有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/TST 著作权归作者所有。请勿转载和采集!