连续地址数据(数组或者malloc的内存)作为函数参数
在編程時,一簇連續的內存單元,比如數組或者malloc的內存塊,如下的數組a 或者指針p.
int a[4];
int *p = malloc(4 * sizeof(int));
我們要想修改上述連續的內存塊,可以寫一個函數(一維指針做參數傳入起始地址即可)來搞定。
If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays as formal parameters.
Way-1
Formal parameters as a pointer ?
void myFunction(int *param) {...
}
Way-2
Formal parameters as a sized array ?
void myFunction(int param[10]) {...
}
Way-3
Formal parameters as an unsized array ?
void myFunction(int param[]) {...
}
1. 一維指針做參數
#include <stdio.h>
#define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(arr[0]))void arrayDouble(int *p, int size)
{for (int i=0; i<size; i++){*(p+i) = *(p+i) * 2;}
}void arrayDouble1(int p[], int size)
{for (int i=0; i<size; i++){p[i] = p[i] * 2;}
}void arrayDouble2(int p[4], int size)
{for (int i=0; i<size; i++){p[i] = p[i] * 2;}
}int main()
{int arr[] = {1, 2, 3, 4};for (int i=0; i<ARRAY_SIZE(arr); i++){printf("%d ", arr[i]);}printf("\n");arrayDouble(arr, ARRAY_SIZE(arr));for (int i=0; i<ARRAY_SIZE(arr); i++){printf("%d ", arr[i]);} printf("\n");arrayDouble1(arr, ARRAY_SIZE(arr));for (int i=0; i<ARRAY_SIZE(arr); i++){printf("%d ", arr[i]);}printf("\n");arrayDouble2(arr, ARRAY_SIZE(arr));for (int i=0; i<ARRAY_SIZE(arr); i++){printf("%d ", arr[i]);}printf("\n");return 0;
}
?上述code運行結果:
1 2 3 4?
2 4 6 8?
4 8 12 16?
8 16 24 32?
?
2. 兩維指針做參數
用兩維數組做參數也可以一簇連續的內存單元的值,只是沒有必要,大材小用,炫技而已,或者對指針操作含糊不清。
#include <stdio.h>
#define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(arr[0]))void arrayDouble(int **pp, int size)
{int *p = *pp;for (int i=0; i<size; i++){*(p+i) = *(p+i) * 2;}
}/* arrayDouble1 is the same as arrayDouble,just without temp variable */
void arrayDouble1(int **pp, int size)
{for (int i=0; i<size; i++){*(*pp+i) = *(*pp+i) * 2;}
}int main()
{int arr[] = {1, 2, 3, 4};int *p = &arr[0];for (int i=0; i<ARRAY_SIZE(arr); i++){printf("%d ", arr[i]);}printf("\n");arrayDouble(&p, ARRAY_SIZE(arr));for (int i=0; i<ARRAY_SIZE(arr); i++){printf("%d ", arr[i]);} printf("\n");arrayDouble1(&p, ARRAY_SIZE(arr));for (int i=0; i<ARRAY_SIZE(arr); i++){printf("%d ", arr[i]);} printf("\n");return 0;
}
?運行結果:
1 2 3 4?
2 4 6 8?
4 8 12 16?
總結
以上是生活随笔為你收集整理的连续地址数据(数组或者malloc的内存)作为函数参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿姨洗铁路是哪首歌啊?
- 下一篇: 二维指针操作链表