-1

I have this small question about dereferencing arrays. I have a method in class like this

T* foo()
{
 // create specific array of objects in here
 return (array)
}

foo2()
{
  myNewArray = *foo();
  // exactly the same algorithm as in foo to create checkArray
  cout << sizeof(myNewArray) << sizeof(checkArray) << endl;
}

I get two different results, but I expect them to be the same?

Ok, so the additional information about the code:

vec4* getGridAttr()
{
        float xval = -0.5;
        float yval = -0.75;
        float xval2 = -0.5;
        float yval2 = -0.75;
        vec4 pointsGrid[100];

        for (int i=0;i<42;i++)
        {

          //Draw horizontal lines
          if (i % 2 == 0) pointsGrid[i] = vec4(xval, yval, 0.0,1);
          else if (i % 2 != 0) {
             pointsGrid[i] = vec4((xval+0.75), yval, 0.0,1);
             yval += 0.075;
             }
        }
        for (int j=42;j<64;j++)
        {

          //Draw horizontal lines
          if (j % 2 != 0)
          {
              pointsGrid[j] = vec4(xval2, yval2, 0.0,1);
              xval2 += 0.075;

          }
          else if (j % 2 == 0) {
             pointsGrid[j] = vec4(xval2, -yval2, 0.0,1);

             }

        }
        return (pointsGrid);
}

and in my other method, i have this:

void display( void )
{

vec4 points1[100];
//code here populates points1 exactly the same as in getGridAttributes, 

cout << "points1 : " << sizeof(points1) << "   " << "  pointsFromGridAttr : " << sizeof(*getGridAttr()) << endl;
}

The output is points1 : 1600 pointsFromGridAttr 16

user1039063
  • 213
  • 3
  • 11
  • 5
    How is `myNewArray` defined? How is `checkArray` defined? How is the array created? Pseudo-code won't help us figure out what's going on; what is your real code? – cdhowie Jun 11 '12 at 21:29

2 Answers2

1

Without seeing more code I can't be sure of this, but if you have something like this:

T* arr1 = makeArray();
T arr2[n];

Then arr1 and arr2 would have different sizes. Specifically, arr1 is a pointer, so its size is the size of a pointer, while arr2 is an array, and its size will be the size of a T object times the number of objects in the array.

Although arrays and pointers in C++ can be interchanged in some contexts, they really are different types. T* and T [n] are different types with different sizes. Once an array decays to a pointer, it loses its size information.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

I guess you would like to compare the length of the arrays. The length of a C array should be calculated as sizeof(array_variable) / sizeof(type_of_array_elements) or sizeof(array_variable) / sizeof(one_element), not just as sizeof(array_variable). For details see this SO question.

Try this:

cout << sizeof(myNewArray) / sizeof(myNewArray[0]) << ", " << sizeof(checkArray) / sizeof(checkArray[0]) << endl;
Community
  • 1
  • 1
kol
  • 27,881
  • 12
  • 83
  • 120