0

I am trying to write a loop which runs across all the elements in the array. I learned the concept here. I am facing some difficulty with its execution. I have been trying to debug and I have written the following function as part of that debugging process. The following is my code:

#include <iostream>
using namespace std;

struct Vmul {
    double c[4][4];
};
double Vmulti(double a[4], double d[4]) {
    cout << sizeof(a) << endl;
    cout << sizeof(a[0]) << endl;
    cout << sizeof(a)/ sizeof(a[0]) << endl;
    return 0;
}
int main()
{
    double r[4] = { 1,2,3,4 };
    double q[4] = { 1,2,3,4 };
    Vmulti(r, q);
    return 0;
}

Output:

4
8
0
Press any key to continue . . .

I am unable to figure out why sizeof(a) return only 4? shouldn't it be 8*4? why isn't sizeof giving me the size and instead giving me the number of elements in the array?

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
user6771484
  • 81
  • 2
  • 12
  • 4
    You're measuring the size of a "pointer" (misnomer for arrays, but almost the same thing), which seems to be 4 bytes on your machine. – cs95 Jul 18 '17 at 19:49
  • 1
    See https://stackoverflow.com/questions/1328223/when-a-function-has-a-specific-size-array-parameter-why-is-it-replaced-with-a-p – YYC Jul 18 '17 at 19:50
  • 1
    Your use of `cout` and `<<` tips me off that this isn't a C question. C and C++ are not the same language. – David Hoelzer Jul 18 '17 at 19:56

1 Answers1

7

An error message from a compiler can go a long way:

test.cpp:8:23: warning: sizeof on array function parameter will return size of 'double *' instead of 'double [4]'
      [-Wsizeof-array-argument]
        cout << sizeof(a) << endl;
                      ^
test.cpp:7:22: note: declared here
double Vmulti(double a[4], double d[4]) {
Erich
  • 1,902
  • 1
  • 17
  • 23