Consider
float a[] = { 0.1, 0.2, 0.3};
I am quite confused about the fact that a
is later passed to a function foo(float* A)
. Shouldn't a variable of type float*
point to a single float, right? Like what is mentioned in this tutorial
Good question.
float *
does point to a single float value.
However, in C, you can do pointer arithmetic. So, when you get the value from the first pointer, you can actually go to the next float in memory.
And in an array, all of the floats are laid out contiguously in memory.
So, in order to access the whole array, you just need to get the pointer to the first element in the array and iterate till the end of the array. This is why the size of the array is also passed to the function along with the pointer to the first element of the array.
void do_stuff(float * a, int n)
{
for(int i=0; i<n; ++i)
{
do_stuff_with_current_element(a[i]);
}
}
In C, arrays are contiguous chunks of memory, which means every element is next to each other in memory. So, a pointer to the first element combined with the knowledge of the type of the element lets you denote an array with just a pointer to the first element. Note that this does not include information on length, which is why many C functions that deal with arrays (like memcpy) also take a parameter for the length.
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