I’m currently studying C programming using the textbook C: How to program 6/e.
Now, in the book when discussing arrays, it states that when passing an array, (other than a character array, due to the ‘\0’ character) to a function, it is necessary to pass the number of elements in the array to the function as well
So given my functions
int myfunct(int myary[], int numelements);
int myfunct(int *myary, int numelements);
Assume that ary has been declared with 10 elements and that we are now in the main function.
myfunct(ary, 10);
Is the (int numelements necessary [in either case], and if so why). The book states that it is for the compiler to know the correct number of elements to process, however the book then goes on to not do this in almost all its examples, and is very very inconsistent.
Also,
int myfunct(int myary[][10], int numrows, int numcolumns);
Same question about numrows and numcolumns.
To illustrate further:
#include <stdio.h>
void test(const int ary[]);
int main(void){
int myary[10] = {1,2,3,4,5,6,7,8,9,10};
test(myary);
return 0;
}
void test (const int ary[]){
int i;
for(i = 0; i<10; i++){
printf("The number in array element %d is: %d\n", i, ary[i] );
}
}
This code seems to compile correctly without the additional parameter, but I do not understand why the book would say I need them, and so do many sites. HELP!
It is not necessary & your code will compile even if you do not pass array size as argument to the function.
But it is a good practice to do so.
C does not provide you means of bounds checking for arrays. You can access beyond the bounds of array through array indexing or pointer arithmetic(Under the hood,both are same) and the compiler does not need to warn you about it. But you will end up getting an Undefined Behavior.
So it is important that you only access memory which belongs to your array. To be able to do this you need to keep track of the size of the array.It is the user’s responsibility to do so.
When you pass an array as argument it decays as pointer to first element of the array.
So
sizeof(arg)inside the function will give you the size of the pointer not the array.There is no way you can know the size of the array inside the function(exception of null terminated string, who’s size can be obtained by
strlen) unless you pass it as an argument or through some other bookeeping(like global variable etc).Passing the size as an argument is the most obvious way to do this.