-1

我有一个关于取消引用数组的小问题。我在课堂上有这样的方法

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

我得到两个不同的结果,但我希望它们是相同的?

好的,关于代码的附加信息:

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

在我的其他方法中,我有这个:

void display( void )
{

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

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

输出为 points1 : 1600 pointsFromGridAttr 16

4

2 回答 2

1

如果没有看到更多代码,我无法确定这一点,但如果你有这样的事情:

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

然后arr1arr2会有不同的大小。具体来说,arr1是一个指针,所以它的大小是指针的大小,arr2而是一个数组,它的大小将是一个T对象的大小乘以数组中的对象数。

尽管 C++ 中的数组和指针在某些情况下可以互换,但它们确实是不同的类型。 T*并且T [n]是不同大小的不同类型。一旦数组衰减为指针,它就会丢失其大小信息。

希望这可以帮助!

于 2012-06-11T21:30:00.497 回答
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;
于 2012-06-11T21:32:49.043 回答