2

If I mention

int ar[100]={1,1};

and I want to know the number of elements present in it rather than the size of it, what commands should I use?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

4 Answers4

7

In case of an array, the size is always the number of elements multiplied by the size of each element. Neither of them (number of element or size) vary, once it is defined.

If you meant to find out the meaningful (to you) elements present in the array, well, you need to have a sentinel value somewhere (thereby marking the end of valid data entry), and using a loop, you need to count the valid elements yourself.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2
int array[3] = {1,2}; //1,2,0

Since the default initializes the array elements to 0, you can count the non-zero values to be the number of elements.

But, consider

int array[4] = {0,1,2}; //0,1,2,0

You'll need a way to determine which zeros are the meaningful ones. Probably, the last zeros are useless.

But consider

int array[4] = {0,1,0}; //0,1,0,0

The 0 at array[2] is intentional. Different ball game. It all depends on you to determine which zeros matter.

Acha Bill
  • 1,255
  • 1
  • 7
  • 20
1

You should implement some sort of counter to track the number of present elements as you add them. There is memory allocated for each element so it is nearly impossible to try and figure out how many of those memory slots are filled.

asdf
  • 2,927
  • 2
  • 21
  • 42
1

Just don't give it the size, like:

int foo[]={1,2,3,4,5};

then compiler will allocate foo to just enough to hold the values in your initializer list, so when you do sizeof(foo)/sizeof(foo[0]) it will do what you want, as long as the array doesn't decay to a pointer. And it actually saves a lot of memory compared with hard coding a 100.

user3528438
  • 2,737
  • 2
  • 23
  • 42