4

I have a C-array like this:

double arr[] = { 0.0, 0.1, 0.2, 0.5, 0.1, 0.2, 0.3, 0.4, 0.2, 0.0, 0.1, 0.3 }; 

Is it safe to get the number of elements like this?

int numElements = sizeof(arr)/sizeof(arr[0]); 

Or is there a better way?

1

4 Answers 4

5

This is the best way. Even it is suggested in C programming book by Dennis ritchie.

Sign up to request clarification or add additional context in comments.

Comments

4

this is a safe way and if you'll look at other question about size of array you'll find this as one of the most common suggestions

and so on.

actually in the last one the suggestion is to do

#define ARRAY_SIZE( array ) sizeof( array ) / sizeof( array[0] ) 

Comments

2

I don't know of any other way to do this, since you don't have a size.

It is reliable, yes.

Comments

2

There are no other better way according to my knowledge, there are no problem in this one.
In java, there are jagged arrays. If it's also in c, then your thought may be correct.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.