Count the number of elements in an array in C

How can I get the number of elements present in an integer array in C after the array is passed to the function? The following code does not work.

size=sizeof(array)/sizeof(array[0]); 
+4
source share
3 answers

In C, you can only get the size of statically distributed arrays, i.e.

 int array[10]; size = sizeof(array) / sizeof(int); 

will give 10.

If your array is declared or passed as int* array , it is impossible to determine its size only by specifying this pointer.

+15
source

Most likely you are doing this inside the function with which you are passing the array.
The array decays as a pointer to the first element of So. You cannot do this inside a function called.

Perform this calculation before calling the function and pass the size as an argument to the function.

+11
source

You are doing it wrong. I will try to explain using a small code example. The explanation is in the code comments:

 int array[100]; int size = sizeof(array) / sizeof(array[0]); // size = 100, but we don't know how many has been assigned a value // When an array is passed as a parameter it is always passed as a pointer. // it doesn't matter if the parameter is declared as an array or as a pointer. int getArraySize(int arr[100]) { // This is the same as int getArraySize(int *arr) { return sizeof(arr) / sizeof(arr[0]); // This will always return 1 } 

As you can see from the above code, you should not use sizeof to find out how many elements are in the array. The right way to do this is to have one (or two) variables to keep track of the size.

 const int MAXSIZE 100; int array[MAXSIZE]; int size = 0; // In the beginning the array is empty. addValue(array, &size, 32); // Add the value 32 to the array // size is now 1. void addValue(int *arr, int *size, int value) { if (size < MAXSIZE) { arr[*size] = value; ++*size; } else { // Error! arr is already full! } } 
+1
source

Source: https://habr.com/ru/post/958755/


All Articles