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.
Advantage of Use Pointers: Pointers are more efficient in handling arrays and data tables. Pointers can be used to return multiple values from a function. Pointers permit references to functions and thus allow passing functions as arguments to other functions.
Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.
When we say that arrays are treated like pointers in C, we mean the following: The array variable holds the address of the first element in the array. It isn't a pointer but it does act like a constant pointer that cannot be changed. Programs often interact with arrays using pointer notation instead of array notation.
Originally Answered: why is pointer indexing faster than array indexing? It's straight forward that array will always will be faster. Because memory allocation of array is continuous. So accessing array is much faster compare to pointer where memory allocation might or might not be continuous.
When you declare a function parameter as an array, the compiler automatically ignores the array size (if any) and converts it to a pointer. That is, this declaration:
int foo(char p[123]);
is 100% equivalent to:
int foo(char *p);
In fact, this isn't about notation but about the actual type:
typedef char array_t[42];
int foo(array_t p); // still the same function
This has nothing to do with how you access p
within the function. Furthermore, the []
operator is not "array notation". []
is a pointer operator:
a[b]
is 100% equivalent to:
*(a + b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With