My question is base on the following code:
int myfunct(int ary[], int arysize)
int myfunct2(int *ary, int arysize)
int main(void){
int numary[10];
myfunct(numary, 10)
myfunct2(numary, 10)
return;
}
int myfunct(int ary[], int arysize) {
//Whatever work is done
}
int myfunct2(int *ary, int arysize) {
// Whatever work is done
}
Is there a reason to use one of these over the other? To elaborate, when concerned with numeric arrays, is there any reason one would want to use pointer notation over array notation. If one uses pointer notation then within the function pointer arithmetic would be used etc.. AND if one uses the [] array notation, one could work with the array as usual. I’m new to programming and I currently do not see any benefit to using the pointer notation.
My precise question, is there any reason to pass a numeric array to a function using pointer notation and therefore using pointer manipulations within the function.
There is no real functional difference between the two notations. In C, when you pass an array variable to a function, it decays to a pointer regardless of the notation. However, in my opinion, the pointer notation is preferable. The problem with
[]notation in function definitions is that, in my opinion, it is somewhat misleading:A ubiquitous mistake among novice C programmers is to assume that
sizeof(array)will give you the number of elements in the array multiplied bysizeof(int), like it would ifarraywere an array variable declared on the stack. But the reality is thatarrayhas been decayed to a pointer, despite the misleading[]notation, and sosizeof(array)is going to besizeof(int*).arrayis really just a pointer to the first element, or possibly a pointer to a single integer allocated anywhere.For example, we could call
foolike this:In which case the
[]notation in the definition offoois kind of misleading.