Element Count of an Array in C++

How do I determine the size of my array in C?

Executive summary:

int a[17];
size_t n = sizeof(a)/sizeof(a[0]);

Full answer:

To determine the size of your array in bytes, you can use the sizeof
operator:

int a[17];
size_t n = sizeof(a);

On my computer, ints are 4 bytes long, so n is 68.

To determine the number of elements in the array, we can divide
the total size of the array by the size of the array element.
You could do this with the type, like this:

int a[17];
size_t n = sizeof(a) / sizeof(int);

and get the proper answer (68 / 4 = 17), but if the type of
a changed you would have a nasty bug if you forgot to change
the sizeof(int) as well.

So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a), the size of the first element of the array.

int a[17];
size_t n = sizeof(a) / sizeof(a[0]);

Another advantage is that you can now easily parameterize
the array name in a macro and get:

#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))

int a[17];
size_t n = NELEMS(a);

How to count instance of items from an array in C?

You're not a million miles away from a good solution. If you already have count available to pass in, that's handy. Otherwise, you can replace it with:

sizeof(input_array)/sizeof(double)

If you know for sure the maximum value that can appear in input array, then the rest of the problem should be pretty easy.

Loop through each item in input_array, like you're already doing. Then increment the index of histwhich relates to the value of the current item, like so:

for(int i = 0; i<count; i++){
hist[input_array[i]]++;
}

This should give the output you're looking for. For future reference, this is called a count occurrence algorithm.

How to count the number of elements in an array in c++?

How to count the number of elements in an array in c++?

You cannot "count" the number of elements in an array.

So I have declared two arrays x[1000] and y[1000]

OK, therefore each array contains exactly 1000 elements each. No more, no less.

What you want is to find out how many times you extracted a pair of numbers from the stream. You'll find that in the variable i, which you have cleverly used to count what you need. You'll want to deduct 1 from that since the last pair of numbers are the ones that reached EOF.


Note that the program will have undefined behaviour if:

  • There are more than 999 pairs of numbers in the file (the array will overflow).
  • The file ends in anything other than a number (the loop condition will never trigger -> the array will overflow).

The off-by-one of i and the problem with the end condition can both be fixed by correct checking of successful extraction before using the extracted value. See: Why is iostream::eof inside a loop condition considered wrong?

Element count of an array in C++

Let's say I have an array arr. When
would the following not give the
number of elements of the array:
sizeof(arr) / sizeof(arr[0])?

One thing I've often seen new programmers doing this:

void f(Sample *arr)
{
int count = sizeof(arr)/sizeof(arr[0]); //what would be count? 10?
}

Sample arr[10];
f(arr);

So new programmers think the value of count will be 10. But that's wrong.

Even this is wrong:

void g(Sample arr[]) //even more deceptive form!
{
int count = sizeof(arr)/sizeof(arr[0]); //count would not be 10
}

It's all because once you pass an array to any of these functions, it becomes pointer type, and so sizeof(arr) would give the size of pointer, not array!


EDIT:

The following is an elegant way you can pass an array to a function, without letting it to decay into pointer type:

template<size_t N>
void h(Sample (&arr)[N])
{
size_t count = N; //N is 10, so would be count!
//you can even do this now:
//size_t count = sizeof(arr)/sizeof(arr[0]); it'll return 10!
}
Sample arr[10];
h(arr); //pass : same as before!

How to count elements in an array in c

If you only want to count all elements: Assuming array can only contain a limited range of integers, declare another array of length the maximum entry in the first array. Iterate through the first array and increment the location in the second array index by the first array, then print out the second array.

Pseudocode:

 int nums[] =  {1,2,2,2,3};

int counts[10]; // assume entries in nums are in range 0..9

for(i = 0; i < length of nums; ++i)
{
num = nums[i];
if(num < 0 or num >= length of counts)
handle this somehow
++counts[num];
}
for(i = 0; i < length of counts; ++i)
{
printf("%d occurs %d times\n", i, counts[i]);
}

If you only want to count a particular value:

int count_in_array(int value, int* array, int length)
{
int count = 0;
int i;
for(i = 0; i < length; ++i)
{
if(array[i] == value)
++count;
}
return count;
}

...
int nums[] = {1,2,2,2,3};
printf("%d occurs %d times\n", 2, count_in_array(2, nums, 5));

Count elements of an unknown type array

because you are checking != NULL i suppose you have an array of pointers. with array of pointer your code could work because you know the size of pointers even if it is a void pointer.

if my assumptions were right you could code it like this:

int nb_elems(void** array) {
void** end = array;
while(*end != NULL) {
end++;
}
return end - array;
}

but this code only works with pointer to pointer or array of pointer.


usage:

int** iptrs = (int**)malloc(3 * sizeof(int*));

iptrs[0] = (int*)malloc(sizeof(int));
*(iptrs[0]) = 42;
iptrs[1] = (int*)malloc(sizeof(int));
*(iptrs[1]) = 23;
iptrs[2] = NULL;

printf("%d", nb_elems(iptrs));

the example prints 2

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

You can't.

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

void f(myStruct* array, size_t siz);

Also notice that in f array is a pointer, while in main it is an array. Arrays and pointers are different things.

Count elements in array in C

Wild guess: you aren't showing your code but you are in fact doing this for the parameter of a function in a 64 bit implementation with 32 bits int. sizeof(array) is the size of the array, sizeof(pointer) is the size of the pointer, not the size of the array to which the pointer may point.

#include <stdio.h>

void f(int* str_numbers)
{
int total = sizeof(str_numbers)/sizeof(str_numbers[0]);
printf("In f: %d\n", total);
}

int main ()
{
int str_numbers[5] = {1,4,8,2,9};
int total = sizeof(str_numbers)/sizeof(str_numbers[0]);
printf ("In main: %d\n", total);
f(str_numbers);
return 0;
}

gives

In main: 5
In f: 2

and it is what I expect on such implementation.

Edit: Using a syntax like print_array(int arr[]) doesn't change the fact that arr is a pointer. There could be a way in C99 to say it is an array, but I don't remember it and VLA have been made optional in C11, to put the standard in agreement with the practice.



Related Topics



Leave a reply



Submit