C语言 如何找到数组存在的项目的长度/数量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5604838/
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 08:20:33  来源:igfitidea点击:

How do I find the length/number of items present for an array?

carrays

提问by neha dhage

Possible Duplicate:
length of array in function argument

可能的重复:
函数参数中的数组长度

My array size is 5. For example:

我的数组大小是 5。例如:

arrCustId[5]

How can I know how many Customer IDs are already present in my array? In short how to find length of array?

我如何知道我的阵列中已经存在多少个客户 ID?总之如何找到数组的长度?

回答by Ben Stott

If the array is statically allocated, use sizeof(array) / sizeof(array[0])

如果数组是静态分配的,请使用 sizeof(array) / sizeof(array[0])

If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.

但是,如果它是动态分配的,不幸的是你运气不好,因为这个技巧总是会返回sizeof(pointer_type)/sizeof(array[0])(在带有 char*s 的 32 位系统上将是 4)你可以a)保持#define(或const)常量,或 b) 然而,保持一个变量。

回答by mgiuca

Do you mean how long is the array itself, or how many customerids are in it?

你的意思是数组本身有多长,或者里面有多少个customerid?

Because the answer to the first question is easy: 5 (or if you don't want to hard-code it, Ben Stott's answer).

因为第一个问题的答案很简单:5(或者,如果您不想对其进行硬编码,请使用 Ben Stott 的答案)。

But the answer to the other question cannot be automatically determined. Presumably you have allocated an array of length 5, but will initially have 0 customer IDs in there, and will put them in one at a time, and your question is, "how many customer IDs have I put into the array?"

但不能自动确定另一个问题的答案。大概你已经分配了一个长度为 5 的数组,但最初会有 0 个客户 ID,并且一次将它们放入一个,你的问题是,“我在数组中放入了多少个客户 ID?”

C can't tell you this. You will need to keep a separate variable, int numCustIds(for example). Every time you put a customer ID into the array, increment that variable. Then you can tell how many you have put in.

C不能告诉你这个。您将需要保留一个单独的变量,int numCustIds(例如)。每次将客户 ID 放入数组时,请增加该变量。然后你可以知道你投入了多少。

回答by CLH

I'm not sure that i know exactly what you mean.

我不确定我是否确切地知道你的意思。

But to get the length of an initialized array,

但是要获得初始化数组的长度,

doesn't strlen(string) work ??

strlen(string) 不起作用??