Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, static array, pointer, length

Can somebody explain to me why this code works?!!

I know A holds &A[0] and it is not a real pointer as if you cout<<&A you would get &A[0], but this result looks very strange to me.

int main()
{
    double A[] = {2.4, 1.2, 4.6, 3.04, 5.7};
    int len =  *(&A+1) - A; // Why is this 5?
    cout << "The array has " << len << " elements." << endl;
    return 0;
} 

And why this code doesn't work? And how can you make it work?

void test(double B[])
{
  int len = *(&B+1) - B;
  cout << len << endl;

}
int main()
{
    double A[] = {2.4, 1.2, 4.6, 3.04, 5.7};
    test(A);
    system("pause");
    return 0;
} 
like image 851
user3112666 Avatar asked Jan 25 '26 10:01

user3112666


2 Answers

The expression is parsed like this:

(*((&A) + 1)) - A

The probably vexing part is that for some (but not all!) parts of this expression, the array decays to a pointer to the first element. So, let's unwrap this:

  1. First thing is taking the address of the array, which gives you a pointer to an array of five elements.

  2. Then, the pointer is incremented (+ 1), which gives the address immediately following the array.

  3. Third, the pointer is dereferenced, which yields a reference to an array of five elements.

  4. Last, the array is subtracted. It is only here that the two operands actually decay to a pointer to their first elements. The two are the length of the array apart, which gives the number of elements as distance.

like image 97
Ulrich Eckhardt Avatar answered Jan 26 '26 23:01

Ulrich Eckhardt


&A takes the address of A itself. The type of A is double[5].

When you take the address of A itself and increment that pointer by 1, you are incrementing it by sizeof(double[5]) bytes. So now you have a pointer to the address following the A array.

When you dereference that pointer, you have a reference to the next double[5] array following A, which is effectively also a double* pointer to the address of A[5].

You are then subtracting the address of A[0] (an array decays into a pointer to its first element), and standard pointer arithmetic gives you 5 elements:

&A[5] - &A[0] = 5
like image 42
Remy Lebeau Avatar answered Jan 26 '26 22:01

Remy Lebeau