数组的大小和指针的大小意味着什么

what does size of array and size of its pointer means?

本文关键字:什么 意味着 数组 指针      更新时间:2023-10-16

最近,我读到代码blow,它让感到困惑

 static string const dirs[6] = {"-n", "-ne", "-se", "-s", "-sw", "-nw" };
 int a = sizeof(dirs)/sizeof(*dirs);

遗嘱等于数组的大小,即6。

所以我的问题是:

  1. sizeof(dirs)代表什么?总数组的大小是多少?

  2. sizeof(*dirs)代表什么?

  1. sizeof(dirs)表示整个阵列的大小
  2. sizeof(*dirs)表示阵列中单个元素的大小

因此,sizeof(*dirs)*元素数量=sizeof(dirs),因为元素数量*每个元素的大小=整个阵列的大小

因此,元素的数量=sizeof(dirs)/sizeof(*dirs)。

what does sizeof(dirs) represent? Is the size of the total array?

是的。

what does sizeof(*dirs) represent?

*dirsdirs[0]相同,因此sizeof(*dirs)是第一个元素的大小。(嗯,每个元素的大小,因为它们是相同的)

sizeof(dirs)/sizeof(*dirs)将是阵列中的元素数量。

sizeof运算符产生所提供操作数的字节大小。由于*dir等于dir[0],因此sizeof(*dirs)将以字节为单位返回第一个数组元素的大小,而sizeof(dirs)将以字节的单位返回所有数组的大小。因此,当你把这些数字除以,你就得到了数组中元素的数量。

关于sizeof运算符的详细信息:http://en.wikipedia.org/wiki/Sizeofhttp://en.cppreference.com/w/cpp/language/sizeof和http://msdn.microsoft.com/en-us/library/4s7x1k91(v=vs.110).aspx

将sizeof运算符应用于引用时,结果与将sizeof应用于对象本身时相同。

如果未定大小的数组是结构的最后一个元素,则sizeof运算符返回不带数组的结构的大小。

sizeof运算符通常用于使用以下形式的表达式计算数组中的元素数:

sizeof array / sizeof array[0]

上述答案的一个重要例外是,如果将dirs传递给函数,则sizeof (*dirs)仍然是数组中一个元素的大小,但sizeof dirs现在将计算为环境中指针类型的大小。这是因为传递到函数中的数组在函数内部使用时只是一个指针。