Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a variable of type float* point to a single float or a sequence of floats?

Tags:

c

pointers

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

enter image description here

like image 682
zell Avatar asked Nov 22 '20 17:11

zell


2 Answers

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]);
  }
}
like image 65
over.sayan Avatar answered Oct 04 '22 20:10

over.sayan


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.

like image 28
Aplet123 Avatar answered Oct 04 '22 19:10

Aplet123