How to find out the size of an array when it is passed as an argument for the function?
An answer to this question on Stack Overflow.
Question
I am passing one dimensional array as an argument for the function.How to find out the size of array in called function?
Below is the sample code :
# include<stdio.h>
int test( int array[ ] ) {
//find the size of an array
}
int main() {
int array[ ] = { 1,2,3,4};
test( array );
return 0;
}
Answer
You have two options:
int len_array1(int array[], int n) {
return n;
}
int len_array2(int array[]) {
int i;
for(i=0;array[i]!=-1;++i) {}
return i;
}
int main() {
int array1[] = {1,2,3,4};
int array2[] = {1,2,3,4,-1};
operate_on_array1(array1,4);
operate_on_array2(array2);
}
You can either store the length of the array somehow (or keep a point to its end) and pass that around, or you can include a special value at the end of the array which it would not otherwise appear in the values within the array.
Many C-style functions prefer the first option (len_array1), but C-style strings use the second option (the special value being the 0x00 or \0 character).