Equivalent of Matlab find function for C arrays - c

I need the equivalent of the Matlab find function (reference) in C for arrays:
ind = find(X) locates all nonzero elements of array X, and returns the
linear indices of those elements in vector ind. If X is a row vector,
then ind is a row vector; otherwise, ind is a column vector. If X
contains no nonzero elements or is an empty array, then ind is an
empty array.
A trivial untested example:
#include <stdlib.h>
#include <time.h>
int main()
{
/* Initialize variables */
int x[25];
int y[25];
/* initialize random seed: */
srand ( time(NULL) );
/* Fill arrays with stuff */
for (i=0;i<25;i++)
{
x[i] = rand();
y[i] = rand();
}
/* Find */
ind = find((x-y) > 0); // Need to figure out how to do this
}
}
Now the kicker is I can't use Boost or C++ containers like vector due to project constraints.

If you are restricted to "vanilla C" (which seems to be the case, from your question) there's nothing like that built-in, you have to write your own version of such function.
But from what I see from your example you need something different than a find function, you want to find the elements differing into x and y. If you strive for flexibility it could be a good idea to write a generic function that checks the given predicate (passed as a function pointer) on two arrays. On the other hand, since in C we have only function pointers (and not functors) performance may suffer.

This should do something close to what you want - returns number of non-zero elements that it has placed in outArray for you. Not quite the same calling signature, but should do what you want. Untested :)
size_t find(int *inArray, int *outArray, size_t arraySize)
{
size_t numElements = 0;
for(int i=0; i<arraySize; i++)
{
if(inArray[i])
{
outArray[numElements++] = inArray[i];
}
}
return numElements;
}

Related

How to convert from double pointer to gsl vector?

So i created this function to convert from double pointer to gsl vector :
void convert_dpvect_gslvect(int N, double *x, gsl_vector *gx)
{
gx->size = N;
for (int i = 0; i < N; i++) {
gx->data[i] = x[i];
}
}
does that make sense? i want to make sure that it coverts correctly. I would really appreciate your help with this.
By looking at the online documentation for gsl lib (link) we can find functions that already do what you want to do. As a general rule, whenever using a type defined in a library you should look for the provided functions to handle such type.
The rationale behind this is that they may take care of errors or other fields that you might forget while implementing your functions.
In your specific case, it seems that you have a vector of double and you want to assign each element to the elements of a gsl_vector. I say this because you do:
gx->data[i] = x[i]; // Access up to N elements from x
What we want is then the provided library function
void gsl_vector_set(gsl_vector *v, const size_t i, double x)
This function sets the value of the i-th element of a vector v to x. If i lies outside the allowed range of 0 to size - 1 then the error handler is invoked. An inline version of this function is used when HAVE_INLINE is defined.
In order to use it we need to be sure that we have allocated enough memory by creating a gsl_vector before. I assume that you have N elements, so the full code would be:
// assume x is already initialized with N elements
gsl_vector* V = gsl_vector_alloc(N);
for (int i = 0; i < N; i++) {
gsl_vector_set( V , i, x[i] );
}
Interestingly enough, by looking at the source code of gsl_vector_set it does something similar to what you came up with, but of course there are some nuisance that are crucial to the library, like checking the range and using the stride to account for different block sizes.
// from https://github.com/ampl/gsl/blob/master/vector/gsl_vector_double
INLINE_FUN
void
gsl_vector_set (gsl_vector * v, const size_t i, double x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}

Passing a 2D array to a function in C?

I need to pass a 2D array to a function.
#include <stdio.h>
#define DIMENSION1 (2)
#define DIMENSION2 (3)
void func(float *name[])
{
for( int i=0;i<DIMENSION1;i++){
for( int j=0;j<DIMENSION2;j++){
float element = name[i][j];
printf("name[%d][%d] = %.1f \n", i, j, element);
}
}
}
int main(int argc, char *argv[])
{
float input_array[DIMENSION1][DIMENSION2] =
{
{0.0f, 0.1f, 0.2f},
{1.0f, 1.1f, 1.2f}
};
func(input_array);
return 0;
}
Dimensions vary depending on the use case, and the func should stay the same.
I tried the above int func(float *[]) but compiler complains expected ‘float **’ but argument is of type ‘float (*)[3]’, and also I get the segmentation fault error at runtime when trying to access the array at element = name[i][j].
What would be the proper signature of my function? Or do I need to call the func differently?
You can use the following function prototype:
int func(int dim1, int dim2, float array[dim1][dim2]);
For this you have to pass both dimensions to the function (you need this values anyhow in the function). In your case it can be called with
func(DIMENSION1, DIMENSION2, input_array);
To improve the usability of the function call, you can use the following macro:
#define FUNC_CALL_WITH_ARRAY(array) func(sizeof(array)/sizeof(*(array)), sizeof(*(array))/sizeof(**(array)), array)
Then you can call the function and it will determine the dimensions itself:
FUNC_CALL_WITH_ARRAY(input_array);
Full example:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#define FUNC_CALL_WITH_ARRAY(array) func(sizeof(array)/sizeof(*(array)), sizeof(*(array))/sizeof(**(array)), array)
int func(int dim1, int dim2, float array[dim1][dim2])
{
printf("dim1 %d, dim2 %d\n", dim1, dim2);
return 0;
}
#define DIMENSION1 (4)
#define DIMENSION2 (512)
int main(int argc, char *argv[])
{
float input_array[DIMENSION1][DIMENSION2];
FUNC_CALL_WITH_ARRAY(input_array);
float input_array2[7][16];
FUNC_CALL_WITH_ARRAY(input_array2);
}
Will print
dim1 4, dim2 512
dim1 7, dim2 16
Dimensions vary depending on the use case, and the func should stay the same.
Use VLA:
void func (int r, int c, float arr[r][c]) {
//access it like this
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
printf ("%f\n", arr[i][j]);
}
}
}
// call it like this
func (DIMENSION1, DIMENSION2, input_array);
You can change your function like this;
int func(float (*arr)[DIMENSION2])
{
}
But also you should change your main code like this;
float input[DIMENSION1][DIMENSION2];//I just upload the dimension1 to dimension2
As noted above in the comment, the key problem is that int func(float *name[]) declares name to be an array of pointers to float.
In this sense, the following modification to main() works:
int main(int argc, char *argv[])
{
float input_array[DIMENSION1][DIMENSION2] =
{
{0.0f, 0.1f, 0.2f},
{1.0f, 1.1f, 1.2f}
};
/* Declare an array of pointers, as this is what func requires at input: */
float* in_p[DIMENSION1];
/* ... and initialize this array to point to first elements of input array: */
for( int i=0;i<DIMENSION1;i++)
in_p[i] = input_array[i];
/* ... and send this array of pointers to func: */
func(in_p);
return 0;
}
This is going to present a very old solution, one that works on every C compiler that exists. The idea goes something like this:
I have multiple pieces of information to keep track of
I should keep them together
This leads us to the idea that we can use a composite type to hold all the related information in one place and then treat that object as a single entity in our code.
There is one more pebble in our bowl of sand:
the size of the information varies
Whenever we have varying-sized objects, dynamic memory tends to get involved.
Arrays vs Pointers
C has a way of losing information when you pass an array around. For example, if you declare a function like:
void f( int a[] )
it means exactly the same thing as:
void f( int * a )
C does not care that the size of the array is lost. You now have a pointer. So what do we do? We pass the size of the array also:
void f( int * a, size_t n )
C99 says “I can make this prettier, and keep the array size information, not just decay to a pointer”. Okay then:
void f( size_t dim1, size_t dim2, float array[dim1][dim2] )
We can see that it is pretty, but we still have to pass around the array’s dimensions!
This is reasonable, as the compiler needs to make the function work for any array, and array size information is kept by the compiler, never by executable code.
The other answers here either ignore this point or (helpfully?) suggest you play around with macros — macros that only work on an array object, not a pointer.
This is not an inherently bad thing, but it is a tricky gotcha: you can hide the fact that you are still individually handling multiple pieces of information about a single object,
except now you have to remember whether or not that information is available in the current context.
I consider this more grievous than doing all the hard stuff once, in one spot.
Instead of trying to juggle all that, we will instead use dynamic memory (we are messing with dynamic-size arrays anyway, right?)
to create an object that we can pass around just like we would with any other array.
The old solution presented here is called “the C struct hack”. It is improved in C99 and called “the flexible array member”.
The C struct hack has always worked with all known compilers just fine, even though it is technically undefined behavior.
The UB problem comes in two parts:
writing past the end of any array is unchecked, and therefore dangerous, because the compiler cannot guarantee you aren’t doing something stupid outside of its control
potential memory alignment issues
Neither of these are an actual issue. The ‘hack’ has existed since the beginning (much to Richie’s reported chagrin, IIRC), and is now codified (and renamed) in C99.
How does this magic work, you ask?
Wrap it all up in a struct:
struct array2D
{
int rows, columns;
float values[]; // <-- this is the C99 "flexible array member"
};
typedef struct array2D array2D;
This struct is designed to be dynamically-allocated with the required size. The more memory we allocate, the larger the values member array is.
Let’s write a function to allocate and initialize it properly:
array2D * create2D( int rows, int columns )
{
array2D * result = calloc( sizeof(array2D) + sizeof(float) * rows * columns, 1 ); // The one and only hard part
if (result)
{
result->rows = rows;
result->columns = columns;
}
return result;
}
Now we can create a dynamic array object, one that knows its own size, to pass around:
array2D * myarray = create2D( 3, 4 );
printf( "my array has %d rows and %d columns.\n", myarray->rows, myarray->columns );
free( myarray ); // don’t forget to clean up when we’re done with it
The only thing left is the ability to access the array as if it were two-dimensional.
The following function returns a pointer to the desired element:
float * index2D( array2D * a, int row, int column )
{
return a->values + row * a->columns + column; // == &(a->values[row][column])
}
Using it is easy, if not quite as pretty as the standard array notation.
But we are messing with a compound object here, not a simple array, and it goes with the territory.
*index2D( myarray, 1, 3 ) = M_PI; // == myarray[ 1 ][ 3 ] = M_PI
If you find that intolerable, you can use the suggested variation:
float * getRow2D( array2D * a, int row )
{
return a->values + row * a->columns; // == a->values[row]
}
This will get you “a row”, which you can array-index with the usual syntax:
getRow2D( myarray, 1 )[ 3 ] = M_PI; // == myarray[ 1 ][ 3 ] = M_PI
You can use either if you wish to pass a row of your array to a function expecting only a 1D array of floats:
void some_function( float * xs, int n );
some_function( index2D( myarray, 1, 0 ), myarray->columns );
some_function( getRow2D( myarray, 1 ), myarray->columns );
At this point you have already seen how easy it is to pass our dynamic 2D array type around:
void make_identity_matrix( array2D * M )
{
for (int row = 0; row < M->rows; row += 1)
for (int col = 0; col < M->columns; col += 1)
{
if (row == col)
*index2D( M, row, col ) = 1.0;
else
*index2D( M, row, col ) = 0.0;
}
}
Shallow vs Deep
As with any array in C, passing it around really only passes a reference (via the pointer to the array, or in our case, via the pointer to the array2D struct).
Anything you do to the array in a function modifies the source array.
If you want a true “deep” copy of the array, and not just a reference to it, you still have to do it the hard way.
You can (and should) write a function to help.
This is no different than you would have to do with any other array in C, no matter how you declare or obtain it.
array2D * copy2D( array2D * source )
{
array2D * result = create2D( source->rows, source->columns );
if (result)
{
for (int row = 0; row < source->rows; row += 1)
for (int col = 0; col < source->cols; col += 1)
*index2D( result, row, col ) = *index2D( source, row, col );
}
return result;
}
Honestly, that nested for loop could be replaced with a memcpy(), but you would have to do the hard stuff again and calculate the array size:
array2D * copy2D( array2D * source )
{
array2D * result = create2D( source->rows, source->columns );
if (result)
{
memcpy( result->values, source->values, sizeof(float) * source->rows * source->columns );
}
return result;
}
And you would have to free() the deep copy, just as you would any other array2D that you create.
This works the same as any other dynamically-allocated resource, array or not, in C:
array2D * a = create2D( 3, 4 ); // 'a' is a NEW array
array2D * b = copy2D( a ); // 'b' is a NEW array (copied from 'a')
array2D * c = a; // 'c' is an alias for 'a', not a copy
...
free( b ); // done with 'b'
free( a ); // done with 'a', also known as 'c'
That c reference thing is exactly how pointer and array arguments to functions work in C, so this should not be something surprising or new.
void myfunc( array2D * a ) // 'a' is an alias, not a copy
Hopefully you can see how easy it is to handle complex objects like variable-size arrays that keep their own size in C, with only a minor amount of work in one or two spots to manage such an object. This idea is called encapsulation (though without the data hiding aspect), and is one of the fundamental concepts behind OOP (and C++). Just because we’re using C doesn’t mean we can’t apply some of these concepts!
Finally, if you find the VLAs used in other answers to be more palatable or, more importantly, more correct or useful for your problem, then use them instead! In the end, what matters is that you find a solution that works and that satisfies your requirements.

proper pattern to use when passing an array to a function

I am currently reading understanding pointers in c, am at the section were the author talks about passing arrays to functions. Out of all the bellow patterns which is best to use and why ? , does it have anything to do with optimisation ?
#include <stdio.h>
void passAsPointerWithSize(int * arr, int size) {
for ( int i = 0; i < size; i++ ) {
printf("%d\n", arr[i]);
}
}
void passAsPointerWithoutSize(int * arr) {
while ( *arr ) {
printf("%d\n", *arr);
arr++;
}
}
void passWithoutPointerWithSize( int arr [] , int size) {
for ( int i = 0; i <= size; i++ ) {
printf("%d\n", arr[i]);
}
}
void passWithoutPointerUsingWhile(int arr []) {
int i = 1;
while ( arr[i] ) {
printf("%d\n", arr[i++]);
}
}
int main() {
int size = 5;
int arr[5] = { 1, 2, 3, 4 , 5};
passAsPointerWithSize(arr, size);
passAsPointerWithoutSize(arr);
passWithoutPointerWithSize(arr, size);
passWithoutPointerUsingWhile(arr);
}
i compiled it with -std=gnu11 -O3
In the context of function parameters, int arr [] is the same as int *arr because when an array is passed as a function argument to a function parameter, it decays into a pointer to its first element.
So the following declaration:
void foo(int * arr, int size);
is equivalent to:
void foo(int arr[], int size);
When it comes to the question whether you need the size parameter, you need it in order to determine the length of the array, unless:
there is a special value stored in the array that act as an indicator for the end of array (the callee would be responsible for checking against this indicator).
the length of the array is already known to the caller.
Otherwise, how could you possibly know how many elements the array contains?
Out of all the bellow patterns which is best to use and why ?
With the points above in mind, the only thing you can always choose is whether to use the int * syntax or the int [] one for the function parameter.
Although both are equivalent (as explained above), some people may argue that using int * could suggest that there is at most one element, whereas int [] could suggest thet there there is at least one element and there could be more than one.
does it have anything to do with optimization ?
No, or at least, not directly, whether you need the size parameter is actually a matter of whether the size of the array is known by the caller or it can be obtained by means of a stored end-of-array indicator.
First see which one is correct! (based on what you posted)
void passAsPointerWithSize(int * arr, int size) {
for ( int i = 0; i < size; i++ ) {
printf("%d\n", arr[i]);
}
}
This is the one not invoking Undefined Behavior.
The ones using while won't stop unless they get an element having value 0. What if the array has no 0's ? Then it will access way beyond the memory (which is the case here). Perhaps this echos back to a time when strings used to be marked with zeros at their end, in any case, it's bad practice.
The other for loop is looping till index<=size accessing array index out of bounds when index = size, again, undefined behavior.
Now back to your question..
The syntax func(int arr[],..) is the same as func(int* arr,...) on the context of passing a 1D-array to a function. Arrays are passed as pointers - it doesn't matter how you specify the signature.
Looping? - it's just a matter of choice.
Typos and other things...
Typos are the <= or the i=1 initialization in one of the functions. did you not want to print the 0-th element? Well i=1 and then you start looping - it missed the 0-th element.
A compiler, when passed an array, deals with a pointer to the first element of the array no matter how you write it so the form doesn't matter
How do I know the size of the array passed?
In any of the cases - when you pass an array to a function as a pointer - there is no way to know the length of the array unless you have some placeholder which marks the end of the array. If that is not the case then you have to obviously somehow know the length of it - which is what you do when you pass a parameter named size in the function.
Readability + Choice + ...
Writing it as arr[] can be used to convey the meaning that it is an array when we will deal with that pointer. You may skim through the code and get an idea about what it is getting as arguments and what it will possibly do. One may argue that a comment can still serve that purpose - that's where choice comes into the picture.
Yeah, some of them won't work (what do you mean by the condition *arr for instance? are you trying to bring back null terminated strings? don't!)
But, actually the fastest one (barring some crazy compiler optimization which I for one have not seen in practice) if you don't care about order is iterating backwards
void passAsPointerWithSize(int *arr, int size) {
for ( int i = size - 1; i > 0; i-- ) {
printf("%d\n", arr[i]);
}
}
That's because it saves a whole CPU clock cycle every loop, since after you reduce i (i--) the answer of comparing to zero (i > 0) is already stored in the registers

How to return multiple types from a function in C?

I have a function in C which calculates the mean of an array. Within the same loop, I am creating an array of t values. My current function returns the mean value. How can I modify this to return the t array also?
/* function returning the mean of an array */
double getMean(int arr[], int size) {
int i;
printf("\n");
float mean;
double sum = 0;
float t[size];/* this is static allocation */
for (i = 0; i < size; ++i) {
sum += arr[i];
t[i] = 10.5*(i) / (128.0 - 1.0);
//printf("%f\n",t[i]);
}
mean = sum/size;
return mean;
}
Thoughts:
Do I need to define a struct within the function? Does this work for type scalar and type array? Is there a cleaner way of doing this?
You can return only 1 object in a C function. So, if you can't choose, you'll have to make a structure to return your 2 values, something like :
typedef struct X{
double mean;
double *newArray;
} X;
BUT, in your case, you'll also need to dynamically allocate the t by using malloc otherwise, the returned array will be lost in stack.
Another way, would be to let the caller allocate the new array, and pass it to you as a pointer, this way, you will still return only the mean, and fill the given array with your computed values.
The most common approach for something like this is letting the caller provide storage for the values you want to return. You could just make t another parameter to your function for that:
double getMean(double *t, const int *arr, size_t size) {
double sum = 0;
for (size_t i = 0; i < size; ++i) {
sum += arr[i];
t[i] = 10.5*(i) / (128.0 - 1.0);
}
return sum/size;
}
This snippet also improves on some other aspects:
Don't use float, especially not when you intend to return a double. float has very poor precision
Use size_t for object sizes. While int often works, size_t is guaranteed to hold any possible object size and is the safe choice
Don't mix output in functions calculating something (just a stylistic advice)
Declare variables close to where they are used first (another stylistic advice)
This is somewhat opinionated, but I changed your signature to make it explicit the function is passed pointers to arrays, not arrays. It's impossible to pass an array in C, therefore a parameter with an array type is automatically adjusted to the corresponding pointer type anyways.
As you don't intend to modify what arr points to, make it explicit by adding a const. This helps for example the compiler to catch errors if you accidentally attempt to modify this array.
You would call this code e.g. like this:
int numbers[] = {1, 2, 3, 4, 5};
double foo[5];
double mean = getMean(foo, numbers, 5);
instead of the magic number 5, you could write e.g. sizeof numbers / sizeof *numbers.
Another approach is to dynamically allocate the array with malloc() inside your function, but this requires the caller to free() it later. Which approach is more suitable depends on the rest of your program.
Following the advice suggested by #FelixPalmen is probably the best choice. But, if there is a maximum array size that can be expected, it is also possible to wrap arrays in a struct, without needing dynamic allocation. This allows code to create new structs without the need for deallocation.
A mean_array structure can be created in the get_mean() function, assigned the correct values, and returned to the calling function. The calling function only needs to provide a mean_array structure to receive the returned value.
#include <stdio.h>
#include <assert.h>
#define MAX_ARR 100
struct mean_array {
double mean;
double array[MAX_ARR];
size_t num_elems;
};
struct mean_array get_mean(int arr[], size_t arr_sz);
int main(void)
{
int my_arr[] = { 1, 2, 3, 4, 5 };
struct mean_array result = get_mean(my_arr, sizeof my_arr / sizeof *my_arr);
printf("mean: %f\n", result.mean);
for (size_t i = 0; i < result.num_elems; i++) {
printf("%8.5f", result.array[i]);
}
putchar('\n');
return 0;
}
struct mean_array get_mean(int arr[], size_t arr_sz)
{
assert(arr_sz <= MAX_ARR);
struct mean_array res = { .num_elems = arr_sz };
double sum = 0;
for (size_t i = 0; i < arr_sz; i++) {
sum += arr[i];
res.array[i] = 10.5 * i / (128.0 - 1.0);
}
res.mean = sum / arr_sz;
return res;
}
Program output:
mean: 3.000000
0.00000 0.08268 0.16535 0.24803 0.33071
In answer to a couple of questions asked by OP in the comments:
size_t is the correct type to use for array indices, since it is guaranteed to be able to hold any array index. You can often get away with int instead; be careful with this, though, since accessing, or even forming a pointer to, the location one before the first element of an array leads to undefined behavior. In general, array indices should be non-negative. Further, size_t may be a wider type than int in some implementations; size_t is guaranteed to hold any array index, but there is no such guarantee for int.
Concerning the for loop syntax used here, e.g., for (size_t i = 0; i < sz; i++) {}: here i is declared with loop scope. That is, the lifetime of i ends when the loop body is exited. This has been possible since C99. It is good practice to limit variable scopes when possible. I default to this so that I must actively choose to make loop variables available outside of loop bodies.
If the loop-scoped variables or size_t types are causing compilation errors, I suspect that you may be compiling in C89 mode. Both of these features were introduced in C99.If you are using gcc, older versions (for example, gcc 4.x, I believe) default to C89. You can compile with gcc -std=c99 or gcc -std=c11 to use a more recent language standard. I would recommend at least enabling warnings with: gcc -std=c99 -Wall -Wextra to catch many problems at compilation time. If you are working in Windows, you may also have similar difficulties. As I understand it, MSVC is C89 compliant, but has limited support for later C language standards.

How can I find the number of elements in an array?

I have an int array and I need to find the number of elements in it. I know it has something to do with sizeof but I'm not sure how to use it exactly.
If you have your array in scope you can use sizeof to determine its size in bytes and use the division to calculate the number of elements:
#define NUM_OF_ELEMS 10
int arr[NUM_OF_ELEMS];
size_t NumberOfElements = sizeof(arr)/sizeof(arr[0]);
If you receive an array as a function argument or allocate an array in heap you can not determine its size using the sizeof. You'll have to store/pass the size information somehow to be able to use it:
void DoSomethingWithArray(int* arr, int NumOfElems)
{
for(int i = 0; i < NumOfElems; ++i) {
arr[i] = /*...*/
}
}
int a[20];
int length;
length = sizeof(a) / sizeof(int);
and you can use another way to make your code not be hard-coded to int
Say if you have an array array
you just need to:
int len = sizeof(array) / sizeof(array[0]);
I personally think that sizeof(a) / sizeof(*a) looks cleaner.
I also prefer to define it as a macro:
#define NUM(a) (sizeof(a) / sizeof(*a))
Then you can use it in for-loops, thusly:
for (i = 0; i < NUM(a); i++)
It is not possible to find the number of elements in an array unless it is a character array. Consider the below example:
int main()
{
int arr[100]={1,2,3,4,5};
int size = sizeof(arr)/sizeof(arr[0]);
printf("%d", size);
return 1;
}
The above value gives us value 100 even if the number of elements is five.
If it is a character array, you can search linearly for the null string at the end of the array and increase the counter as you go through.
In real we can't count how many elements are store in array
But you can find the array length or size using sizeof operator.
But why we can't find how many elements are present in my array.
Because when we initialise an array compiler give memory on our program like a[10] (10 blocks of 4 size) and every block has garbage value if we put some value in some index like a[0]=1,a[1]=2,a[3]=8; and other block has garbage value no one can tell which value is garbage and which value is not garbage that's a reason we cannot calculate how many elements in an array. I hope this will help you to understand. Little concept
Super easy.
Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof().
For example, given an integer array called myArray
int numArrElements = sizeof(myArray) / sizeof(int);
Now, if the data type of your array isn't constant and could possibly change, then make the divisor in the equation use the size of the first value as the size of the data type.
For example:
int numArrElements = sizeof(myArray) / sizeof(myArray[0]);
This way, the code is type agnostic and will function correctly no matter the data type of the array.
I used following code as suggested above to evaluate number of elements in my 2-dimensional array:
#include <stdio.h>
#include <string.h>
void main(void)
{
char strs[3][20] =
{
{"January"},
{"February"},
{""}
};
int arraysize = sizeof(strs)/sizeof(strs[0]);
for (int i = 0; i < arraysize; i++)
{
printf("Month %d is: %s\n", i, strs[i]);
}
}
It works nicely. As far as I know you can't mix up different data types in C arrays and also you should have the same size of all array elements (if I am right), therefore you can take advantage of that with this little trick:
count number of bytes with sizeof() function from whole 2d array (in this case 3*20 = 60 bytes)
count number of bytes with sizeof() function from first array element strs[0] (in this case 20 bytes)
divide whole size with size of one element what will give you number of elements
This snipped should be portable for 2d arrays in C however in other programming languages it could not work because you can use different data types within array with different sizes (like in JAVA).
The question is simple: given a C++ array (e.g. x as in int x[10]), how would you get the number of elements in it?
An obvious solution is the following macro (definition 1):
#define countof( array ) ( sizeof( array )/sizeof( array[0] ) )
I cannot say this isn’t correct, because it does give the right answer when you give it an array. However, the same expression gives you something bogus when you supply something that is not an array. For example, if you have
int * p;
then countof( p ) always give you 1 on a machine where an int pointer and an int have the same size (e.g. on a Win32 platform).
This macro also wrongfully accepts any object of a class that has a member function operator[]. For example, suppose you write
class IntArray {
private:
int * p;
size_t size;
public:
int & operator [] ( size_t i );
} x;
then sizeof( x ) will be the size of the x object, not the size of the buffer pointed to by x.p. Therefore you won’t get a correct answer by countof( x ).
So we conclude that definition 1 is not good because the compiler does not prevent you from misusing it. It fails to enforce that only an array can be passed in.
What is a better option?
Well, if we want the compiler to ensure that the parameter to countof is always an array, we have to find a context where only an array is allowed. The same context should reject any non-array expression.
Some beginners may try this (definition 2):
template <typename T, size_t N>
size_t countof( T array[N] )
{
return N;
}
They figure, this template function will accept an array of N elements and return N.
Unfortunately, this doesn’t compile because C++ treats an array parameter the same as a pointer parameter, i.e. the above definition is equivalent to:
template <typename T, size_t N>
size_t countof( T * array )
{
return N;
}
It now becomes obvious that the function body has no way of knowing what N is.
However, if a function expects an array reference, then the compiler does make sure that the size of the actual parameter matches the declaration. This means we can make definition 2 work with a minor modification (definition 3):
template <typename T, size_t N>
size_t countof( T (&array)[N] )
{
return N;
}
This countof works very well and you cannot fool it by giving it a pointer. However, it is a function, not a macro. This means you cannot use it where a compile time constant is expected. In particular, you cannot write something like:
int x[10];
int y[ 2*countof(x) ]; // twice as big as x
Can we do anything about it?
Someone (I don’t know who it is – I just saw it in a piece of code from an unknown author) came up with a clever idea: moving N from the body of the function to the return type (e.g. make the function return an array of N elements), then we can get the value of N without actually calling the function.
To be precise, we have to make the function return an array reference, as C++ does not allow you to return an array directly.
The implementation of this is:
template <typename T, size_t N>
char ( &_ArraySizeHelper( T (&array)[N] ))[N];
#define countof( array ) (sizeof( _ArraySizeHelper( array ) ))
Admittedly, the syntax looks awful. Indeed, some explanation is necessary.
First, the top-level stuff
char ( &_ArraySizeHelper( ... ))[N];
says _ArraySizeHelper is a function that returns a reference (note the &) to a char array of N elements.
Next, the function parameter is
T (&array)[N]
which is a reference to a T array of N elements.
Finally, countof is defined as the size of the result of the function _ArraySizeHelper. Note we don’t even need to define _ArraySizeHelper(), -- a declaration is enough.
With this new definition,
int x[10];
int y[ 2*countof(x) ]; // twice as big as x
becomes valid, just as we desire.
Am I happy now? Well, I think this definition is definitely better than the others we have visited, but it is still not quite what I want. For one thing, it doesn’t work with types defined inside a function. That’s because the template function _ArraySizeHelper expects a type that is accessible in the global scope.
I don’t have a better solution. If you know one, please let me know.
#include<stdio.h>
int main()
{
int arr[]={10,20,30,40,50,60};
int *p;
int count=0;
for(p=arr;p<&arr+1;p++)
count++;
printf("The no of elements in array=%d",count);
return 0;
}
OUTPUT=6
EXPLANATION
p is a pointer to a 1-D array, and in the loop for(p=arr,p<&arr+1;p++)
I made p point to the base address. Suppose its base address is 1000; if we increment p then it points to 1002 and so on. Now coming to the concept of &arr - It basically represents the whole array, and if we add 1 to the whole array i.e. &arr+1, it gives the address 1012 i.e. the address of next 1-D array (in our case the size of int is 2), so the condition becomes 1000<1012.
So, basically the condition becomes
for(p=1000;p<1012;p++)
And now let's check the condition and count the value
1st time p=1000 and p<1012 condition is true: enter in the loop, increment the value of count to 1.
2nd time p=1002 and p<1012 condition is true: enter in the loop, increment the value of count to 2.
...
6th time p=1010 and p<1012 condition is true: enter in the loop, increment the value of count to 6.
Last time p=1012 and p<1012 condition is false: print the value of count=6 in printf statement.
sizeof returns the size in bytes of it's argument. This is not what you want, but it can help.
Let's say you have an array:
int array[4];
If you apply sizeof to the array (sizeof(array)), it will return its size in bytes, which in this case is 4 * the size of an int, so a total of maybe 16 bytes (depending on your implementation).
If you apply sizeof to an element of the array (sizeof(array[0])), it will return its size in bytes, which in this case is the size of an int, so a total of maybe 4 bytes (depending on your implementation).
If you divide the first one by the second one, it will be: (4 * the size of an int) / (the size of an int) = 4; That's exactly what you wanted.
So this should do:
sizeof(array) / sizeof(array[0])
Now you would probably like to have a macro to encapsulate this logic and never have to think again how it should be done:
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
You need the parentheses enclosing all the macro as in any other complex macro, and also enclosing every variable, just to avoid unexpected bugs related to operators precedence.
Now you can use it on any array like this:
int array[6];
ptrdiff_t nmemb;
nmemb = ARRAY_SIZE(array);
/* nmemb == 6 */
Remember that arguments of functions declared as arrays are not really arrays, but pointers to the first element of the array, so this will NOT work on them:
void foo(int false_array[6])
{
ptrdiff_t nmemb;
nmemb = ARRAY_SIZE(false_array);
/* nmemb == sizeof(int *) / sizeof(int) */
/* (maybe ==2) */
}
But it can be used in functions if you pass a pointer to an array instead of just the array:
void bar(int (*arrptr)[7])
{
ptrdiff_t nmemb;
nmemb = ARRAY_SIZE(*arrptr);
/* nmemb == 7 */
}
void numel(int array1[100][100])
{
int count=0;
for(int i=0;i<100;i++)
{
for(int j=0;j<100;j++)
{
if(array1[i][j]!='\0')
{
count++;
//printf("\n%d-%d",array1[i][j],count);
}
else
break;
}
}
printf("Number of elements=%d",count);
}
int main()
{
int r,arr[100][100]={0},c;
printf("Enter the no. of rows: ");
scanf("%d",&r);
printf("\nEnter the no. of columns: ");
scanf("%d",&c);
printf("\nEnter the elements: ");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
scanf("%d",&arr[i][j]);
}
}
numel(arr);
}
This shows the exact number of elements in matrix irrespective of the array size you mentioned while initilasing(IF that's what you meant)
we can find number of elements in array only if array is declared in this format
int a[]={1,2,3,4,5,6};
number of element in array is
n=sizeof(a) / sizeof(a[0]);
we should no able to calculate array size if it is declared like this int a[10]={1,2,3,4,5,6}
i mostly found a easy way to execute the length of array inside a loop just like that
int array[] = {10, 20, 30, 40};
int i;
for (i = 0; i < array[i]; i++) {
printf("%d\n", array[i]);
}
If we don't know the number of elements in the array and when the input is given by the user at the run time. Then we can write the code as
C CODE:
while(scanf("%d",&array[count])==1) {
count++;
}
C++ CODE:
while(cin>>a[count]) {
count++;
}
Now the count will be having the count of number of array elements which are entered.
Assuming you have an array with elements 1,3,4.
To know its length, you'd need to use the sizeof function as follows:
int myArray[] = {1,3,4};
int len = sizeof(myArray) / sizeof(myArray[0]);
You can check the number of elements by printing the output as follows:
cout<<"This array has " << len << " elements";
The full program would be as follows:
#include <iostream>
using namespace std;
int main()
{
int myArray[] = {1,3,4};
int len = sizeof(myArray) / sizeof(myArray[0]);
cout<<"The array has " << len << "elements";
return 0;
}
Actually, there is no proper way to count the elements in a dynamic integer array. However, the sizeof command works properly in Linux, but it does not work properly in Windows. From a programmer's point of view, it is not recommended to use sizeof to take the number of elements in a dynamic array. We should keep track of the number of elements when making the array.

Resources