C语言 C:查找数组中元素的数量[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4081100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:53:26  来源:igfitidea点击:

C: finding the number of elements in an array[]

carrayspointers

提问by Lavi Avigdor

In C: How do you find the number of elements in an array of structs, after sending it to a function?

在 C 中:在将结构数组发送给函数后,如何找到它的数量?

int main(void) {
  myStruct array[] = { struct1, struct2, struct3, struct4, struct5, struct6 };
  printf("%d\n", sizeof(array));
  printf("%d\n", sizeof(array[0]));
  f(array);
}
void f(myStruct* array) {
  printf("%d\n", sizeof(array));
  printf("%d\n", sizeof(array[0]));
}

For some reason the printf in main shows different results than the printf in f. My need is to know how many elements are in the array.

出于某种原因,main 中的 printf 显示出与 f 中的 printf 不同的结果。我需要知道数组中有多少元素。

回答by pmg

You can't.

你不能。

You have to pass the size to the function, eg:

您必须将大小传递给函数,例如:

void f(myStruct* array, size_t siz);

Also notice that in farray is a pointer, while in mainit is an array. Arrays and pointers are different things.

还要注意 in farray 是一个指针,而 in mainit 是一个数组。数组和指针是不同的东西。

回答by PaulJWilliams

In f arrayis a pointer, in main arrayis an array.

在 f 中array是一个指针,在 main 中array是一个数组。

回答by Zan Lynx

You must pass that data as a separate parameter to the function. In C and C++ as soon as an array is passed to a function the array degenerates into a pointer. Pointers have no notion of how many elements are in the array they point to.

您必须将该数据作为单独的参数传递给函数。在 C 和 C++ 中,只要将数组传递给函数,数组就会退化为指针。指针不知道它们指向的数组中有多少元素。

A common way to get the size is to declare the array and then immediately get the array element count by dividing the total size by the size of one element. Like this:

获取大小的一种常用方法是声明数组,然后通过将总大小除以一个元素的大小立即获取数组元素数。像这样:

struct my_struct my_struct_array[] = {
 {"data", 1, "this is data"},
 {"more data", 2, "this is more data"},
 {"yet more", 0, "and again more data"}
};
const size_t my_struct_array_count = sizeof(my_struct_array)/sizeof(my_struct_array[0]);

回答by Apaar

Note that in main(), array refers to the actual array and so sizeof() gives the required answer.

请注意,在 main() 中,数组指的是实际数组,因此 sizeof() 给出了所需的答案。

But when you pass it as function parameter,you are actually passing the address of the first element of the array which is stored in the pointer variable 'array'.
So now sizeof() gives the size of pointer variable which is why it differs from actual answer.

但是当你将它作为函数参数传递时,你实际上是在传递存储在指针变量“array”中的数组第一个元素的地址。
所以现在 sizeof() 给出了指针变量的大小,这就是它与实际答案不同的原因。

Possible solution can be to

可能的解决方案是

1.Declare the array globally

1.全局声明数组

2.Pass the array size as function parameter Hope it helps!

2.将数组大小作为函数参数传递希望它有帮助!

回答by Jean-Marc Valin

In the code above, function f() has no way of knowing how many elements were in your original array. It's a feature of the language and there's no way around it. You'll have to pass the length.

在上面的代码中,函数 f() 无法知道原始数组中有多少元素。这是语言的一个特性,没有办法绕过它。你必须传递长度。

回答by David Harris

As the C referencesays, you cannot do this unless either the last element is unique or you pass a count of array elements to the function.

正如C 参考所说,除非最后一个元素是唯一的,或者您将数组元素的计数传递给函数,否则您不能这样做。

回答by bkilinc

you have to end the array with a special value and in called function you have to count up to that value that is how strlen() works it counts up to NULL '\0' value.

您必须以特殊值结束数组,并且在被调用的函数中,您必须计数到该值,这就是 strlen() 的工作方式,它计数到 NULL '\0' 值。

回答by Ursa Major

You may use a format for your array. I am using string elements, it should work for struct.

您可以为数组使用一种格式。我正在使用字符串元素,它应该适用于结构。

#define NULL ""
#define SAME 0

static char *check[] = {
      "des", "md5", "des3_ede", "rot13", "sha1", "sha224", "sha256",
      "blowfish", "twofish", "serpent", "sha384", "sha512", "md4", "aes",
      "cast6", "arc4", "michael_mic", "deflate", "crc32c", "tea", "xtea",
      "khazad", "wp512", "wp384", "wp256", "tnepres", "xeta",  "fcrypt",
      "camellia", "seed", "salsa20", "rmd128", "rmd160", "rmd256", "rmd320",
      "lzo", "cts", "zlib", NULL
 }; // 38 items, excluding NULL

in main ( )

在主要 ( )

char **algo = check;
int numberOfAlgo = 0;


while (SAME != strcmp(algo[numberOfAlgo], NULL)) {
    printf("Algo: %s \n", algo[numberOfAlgo++]);
}

printf("There are %d algos in the check list. \n", numberOfAlgo);

You should get the output:

你应该得到输出:

Algo: des 
   :
   :
Algo: zlib 

There are 38 algos in the check list.

Alternatively, if you do not want to use the NULL , do this instead:

或者,如果您不想使用NULL,请改为执行以下操作:

numberOfAlgo = 0;

while (*algo) {
    printf("Algo: %s \n", *algo);
    algo++;         // go to the next item
    numberOfAlgo++; // count the item
}

printf("There are %d algos in the check list. \n", numberOfAlgo);

回答by Ursa Major

As an example to your solution:

作为您的解决方案的示例:

Given

给定的

struct contain {
char* a;        //
int allowed;    //

struct suit {
   struct t {
          char* option;
          int count;
   } t;

   struct inner {
          char* option;
          int count;
   } inner;
} suit;
};

// eg. initialized

// 例如。初始化

     struct contain structArrayToBeCheck[] = {
    {
        .a = "John",
        .allowed = 1,

        .suit = {
            .t = {
                .option = "ON",
                .count = 7
            },

            .inner = {
                .option = "OFF",
                .count = 7
            }
        }
    },
    {
        .a = "John",
        .allowed = 1,

        .suit = {
            .t = {
                .option = "ON",
                .count = 7
            },

            .inner = {
                .option = "OFF",
                .count = 7
            }
        }
    },
    {
        .a = "John",
        .allowed = 1,

        .suit = {
            .t = {
                .option = "ON",
                .count = 7
            },

            .inner = {
                .option = "OFF",
                .count = 7
            }
        }
    },
    {
        .a = "John",
        .allowed = 1,

        .suit = {
            .t = {
                .option = "ON",
                .count = 7
            },

            .inner = {
                .option = "OFF",
                .count = 7
            }
        }
    }

};

in main()

在主()

printf("Number of Struct within struct array: %d \n", sizeof(structArrayToBeCheck)/sizeof(struct contain));

gives you the correct answer.

给你正确的答案。

回答by Pablo Santa Cruz

You can't tell number of elements in an array in Cconsistently. Specially if you pass the array around through pointers.

你不能在C 中一致地告诉数组中的元素数。特别是如果您通过指针传递数组。

Usually, if you mustuse array size in a function, pass it as a parameter to it.

通常,如果您必须在函数中使用数组大小​​,请将其作为参数传递给它。