16

Possible Duplicate:
length of array in function argument

My array size is 5. For example:

arrCustId[5]

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

Community
  • 1
  • 1
neha dhage
  • 161
  • 1
  • 1
  • 3

3 Answers3

27

If the array is statically allocated, use 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.

Ben Stott
  • 2,218
  • 17
  • 23
13

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

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

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?"

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.

mgiuca
  • 20,958
  • 7
  • 54
  • 70
  • 1
    +1 for simplicity. If you want to know how many customers there are, just remember how many you put in there. – sam hocevar Apr 09 '11 at 12:11
-6

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 ??

CLH
  • 89
  • 4
  • strlen is used only on strings because it looks in the initialized array for the NULL terminator (\0). So it should only be used with char * since they are kinda special. – judda Apr 09 '11 at 15:54
  • well, you sorta right :) but do realize that a string is actually an array of characters... – Joe DF Apr 19 '13 at 01:14
  • But is there a `\0` in other types of arrays? – Charles Nov 18 '15 at 15:13