zell
zell

Reputation: 10204

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

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

Upvotes: 5

Views: 153

Answers (4)

Adrian Mole
Adrian Mole

Reputation: 51864

A float* variable (when properly initialized or assigned) does, indeed, point to a single float variable. However, that single variable could be the first element of an array of float data.

Further, when you give an array as an argument to a function, the array implicitly decays to a pointer to its first element. So, calling your foo function with the array, a, as its parameter, is passing a pointer to that array's first element (a float item) - so the argument fully satisfies the function's requirement to take a "pointer-to-float" parameter.

Upvotes: 1

over.sayan
over.sayan

Reputation: 106

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]);
  }
}

Upvotes: 4

Faruk Z.
Faruk Z.

Reputation: 9

The pointer reaches the base adress and checks the type of your variable. Every step it sums with your variable byte. So in real you have just your base adress and variable information.

Upvotes: 1

Aplet123
Aplet123

Reputation: 35540

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.

Upvotes: 3

Related Questions