In C, how can I pass an array with unknown size to a function (by reference)?
The size of the array is only determined inside the function.
In C, how can I pass an array with unknown size to a function (by reference)?
The size of the array is only determined inside the function.
If the array is a null terminated character array then you can use strlen
to calculate the length of that character array. Otherwise you need to use a delimiter to know the end of the array and find length using a loop to the delimiter.
NOTE: No pass by reference in C.
You have to pass the starting address of the array along with the number of arguments such as the following.
void f (int* array, int n) {
int i, x;
for (i = 0; i < n; i++) {
x = array[i]; // use x
...
}
...
}
Alternative: You would have to agree on a standard EOD (End of Data) marker. In this case you may not pass the length of the array explicitly, but rather rely on the value to check for the end of the array. An example is the 0 terminated string (char array of C).
#define END_OF_ARRAY -1
void f (int* array) {
int i;
while (array[i] != END_OF_ARRAY) {
// use array[i]
...
i++;
}
...
}
You'll have to malloc
the array inside the function. Then either:
[examples given for array of int; adapt accordingly]
(i) return a pointer to it:
int* f(void) {
int *array;
.
.
.
array = malloc(length * sizeof int);
.
.
.
return array;
}
or
(ii) store it inside a pointer passed by the caller
void f(int **array) { // yes, double pointer
.
.
.
*array = malloc(length * sizeof int); // here malloc's your array and store it in *array
.
.
.
}
Don't forget to free
this array after you finished with it.
Edit: the callee would be:
(i)
int *array; // can't use the array yet
.
.
.
array = f(); // now it's available for use
.
.
.
free(array); // no longer available
(ii)
int *array; // can't use the array yet
.
.
.
f(&array); // now it's available for use
.
.
.
free(array); // no longer available