[英]How to Find Dimension of a Multiple Dimension Array in C
I declared a 2-dimensional array like this: 我宣布了一个像这样的二维数组:
char *array[][3] = {
{"a", "b", "c"},
{"d", "e", "f"},
{"u", "v", "w"},
{"x", "y", "z"}};
How do I find out the first dimension? 我如何找到第一个维度?
Example: * 示例: *
#include <stdio.h>
int main(void) {
int array[4];
printf("%zd\n", sizeof array / sizeof array[0]);
printf("%zd\n", sizeof (int));
printf("%ld\n", (long)(sizeof array / sizeof array[0]));
return 0;
}
type-name
, even though sizeof
is an operator not a function.
type-name
,则需要parens,即使sizeof
是运算符而不是函数。
But every place where a type-name
appears in the C grammar (declarators don't use that production) then parens are required around it.
type-name
每个地方(声明者都不使用该生产),然后需要围绕它的parens。
Because there isn't a separate production for a type-name-in-parens in the semi-formal grammars used for the various C specs, they specify the needed parens in the productions that define things like sizeof
, generic-associations
, and cast-expressions
.
sizeof
, generic-associations
和cast-expressions
。
But those parens are really there in order to be able to parse a type within the expression grammar.
Why don't you give: 你为什么不给:
sizeof(array) / sizeof(char*) / 3
a shot? 一枪?
This is assuming you know the data type (char*) and other dimension (3). 这假设您知道数据类型(char *)和其他维度(3)。
You divide the size of the structure by the size of each element to get the total number of elements, then divide it by the first dimension, giving you the second. 您可以将结构的大小除以每个元素的大小以获得元素的总数,然后将其除以第一个维度,得到第二个维度。
Aside: my original answer used 'sizeof("a")'
which was, of course, wrong, since it was the size of the array (2, being 'a' and '\\0'), not the pointer (4 on my hideously outdated 32-bit machine). 旁白:我的原始答案使用
'sizeof("a")'
当然是错误的,因为它是数组的大小(2,是'a'和'\\ 0'),而不是指针(4)我可怕的过时的32位机器)。 But I love the way I got two upvotes for that wrong answer - don't you bods actually check the answers here before voting? 但我喜欢我得到两个赞成错误答案的方式 - 在投票之前,你不是真的在这里检查答案吗? :-)
:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.