用于测量2D阵列的Sizeof运算符

时间:2017-05-30 00:39:56

标签: arrays pointers memory sizeof

我目前正在修课程,我们正在学习指针。以下是我教授给我们的一个例子。

int b[3][3];  //Assume integers and memory addresses are 4 bytes
cout << sizeof(b) << endl;  // 36 bytes
cout << sizeof(b+0) << endl;  // 4 bytes
cout << sizeof(*(b+0)) << endl;  //12 bytes

我有两个问题:

  1. 我尝试了第二个(sizeof(b+0))而它给了我8个?那是怎么回事?

  2. 此外,我想了解第三个背后的逻辑(sizeof(*(b+0));它是12,因为它是第一行的总和?由于有3个整数,每个int是4个字节,因此它总共返回12个字节?

  3. 非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

  

尺寸功能为..

sizeof运算符,而不是函数。阅读Why is sizeof considered as an operator?

中的更多内容
  

它给了我8个呢?

它衰减到指针

  

是12,因为它是第一行的总和吗?

是。这就像拥有3个整数的一维数组。

您可能也想检查这些:

// List requests by hour
var q = new W3CReader(textReader).Read()
             .GroupBy(r => r.UtcTime().RoundUp(TimeSpan.FromHours(1)))
             .Select(g => new
             {
                    Hour = g.Key,
                    Count = g.Count()
             });
foreach (var r in q)
{
    Console.WriteLine("{0}\t{1}", r.Hour, r.Count);
}

关于警告:

“此警告告诉您,如果您致电Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp main.cpp:8:21: warning: sizeof on pointer operation will return size of 'int (*)[3]' instead of 'int [3][3]' [-Wsizeof-array-decay] cout << sizeof(b+0) << endl; // 4 bytes ~^ 1 warning generated. Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 36 8 12 4 // sizeof(int) 8 // sizeof(int*) ,您将无法获得数组的大小,但会获得sizeof(int[])指针的大小。”

取自answer

答案 1 :(得分:0)

1)在具有64位地址的系统中,指针有8个字节,64/8。

2)2D数组存储为指向数组的指针数组。所以当你执行*(b + 0)时,它会给你数组b的第一个位置的内容,这是一个3个整数的数组。 *(b + 0)相当于b [0]。