I need to pass an integer to a function that only accepts arrays

The question arose about functions and arrays. Suppose I have it

int example1(unsigned int hold[], size) { .... } 

and then in another function that I want to call in my example 1, but instead of passing an array, I want to pass an integer, so this

 int example2(unsigned int hold) { int i; for(i = 0; i < 10; i++) example1(hold,i); } 

how can i make it work

+7
c function arrays
source share
3 answers

Your example1 function takes a pointer to the first element of an int array. Since a pointer to one variable is essentially equivalent to a pointer to the first element of the array, you can simply pass the address of this single int with a size of 1:

 example(&hold, 1); 
+11
source share

A pointer to a value can be passed instead of an array of only 1 element; your loop makes example1 assume an array larger than 1.

Since you pass i as the size, create an array of i elements, set it with some values, and pass it to example1 , for example:

 for(size_t i = 0 ; i < 10 ; i++) { unsigned int arg[i+1]; for (size_t j = 0 ; j != i ; j++) { arg[j] = value; } example1(arg, i); } 
+5
source share

In C99, you can also use a compound literal :

 example1((unsigned int[]){hold}, 1); 
0
source share

All Articles