简体   繁体   English

如何在C中找到多维数组的维数

[英]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? 我如何找到第一个维度?

sizeof array / sizeof array[0] sizeof array / sizeof数组[0]

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


*You need the parens if the operand is a 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. 但是在C语法中出现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 . 因为在用于各种C规范的半正式语法中没有针对类型名称的单独生成,所以它们在生成中指定了所需的parens,这些parens定义了诸如sizeofgeneric-associationscast-expressions But those parens are really there in order to be able to parse a type within the expression grammar. 但是那些parens确实存在,以便能够解析表达式语法中的类型。 They are part of the syntax for something you might call "type expressions," but given the limited use of such things they don't actually have any such production or term. 它们是你可能称之为“类型表达式”的语法的一部分,但考虑到这些东西的使用有限,它们实际上并没有任何这样的产生或术语。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM