Say i have a array of integer arr and we want to pass it function x.
#include <stdio.h> void x(int *pa); int main() { int arr[5] = {10, 3, 5, 2, 90}; int i; printf("Arr before call to x\n"); for(i = 0; i < 5; i++) { printf("arr[%d]:%d, ", i, arr[i]); } printf("\n"); x(arr); printf("Arr after call to x\n"); for(i = 0; i < 5; i++) { printf("arr[%d]:%d, ", i, arr[i]); } printf("\n"); return 0; } void x(int *pa) { printf("Content of pa[0] is %d, via pointer %d\n", pa[0], *pa); printf("Content of pa[1] is %d, via pointer %d\n", pa[1], *(pa+1)); pa[0] = 20; *(pa+1) = 7; }
Output of the above program is
Arr before call to x arr[0]:10, arr[1]:3, arr[2]:5, arr[3]:2, arr[4]:90, Content of pa[0] is 10, via pointer 10 Content of pa[1] is 3, via pointer 3 Arr after call to x arr[0]:20, arr[1]:7, arr[2]:5, arr[3]:2, arr[4]:90,
Array name arr is pointer to array, it refers to the address of the array. Address arr is passed to the function x, which is received via integer pointer pa in function x. In function x we can accessed array in array method pa[0] and pointer method *(pa + 1).
Note that using the pointer(pa), function x can change the content of array arr. Array arr is printed before and after call to x and see the arr[0] and arr[1] is changed by call to x.
In above program, function x would not know the how big is the array. Hence following
pa[100] = 10;
would be syntactically correct and compiler would not complain. But this would lead to memory corruption. Solution to above issue is by passing array length along with the array to function. Hence lets re-write the above program by passing length. Lets also introduce new function print_arr to print array.
#include <stdio.h> void print_arr(int *pa, int len); void x(int *pa, int len); int main() { int arr[5] = {10, 3, 5, 2, 90}; int i; printf("Arr before call to x\n"); print_arr(arr, 5); x(arr, 5); printf("Arr after call to x\n"); print_arr(arr, 5); return 0; } void print_arr(int *pa, int len) { int i; for(i = 0; i < len; i++) { printf("a[%d]: %d, ", i, pa[i]); } printf("\n"); } void x(int *pa, int len) { printf("pa points to array of len %d\n", len); printf("Content of pa[0] is %d, via pointer %d\n", pa[0], *pa); printf("Content of pa[1] is %d, via pointer %d\n", pa[1], *(pa+1)); pa[0] = 20; *(pa+1) = 7; }
Output of the above program is
Arr before call to x a[0]: 10, a[1]: 3, a[2]: 5, a[3]: 2, a[4]: 90, pa points to array of len 5 Content of pa[0] is 10, via pointer 10 Content of pa[1] is 3, via pointer 3 Arr after call to x a[0]: 20, a[1]: 7, a[2]: 5, a[3]: 2, a[4]: 90,
Function prototype of x could be written as
void x(int pa[], int len);
This is another way of explicitly telling that pa is array. Still pa could be accessed by array method as well as pointer method.
Links
Next Article - C Programming #53: Structure - introduction
Previous Article - C Programming #51: Void pointer
All Article - C Programming
No comments :
Post a Comment