I've read many discussions on passing arrays to functions. They seem to be written for people who are fluent in C. I am a barbarian not yet fluent in C.
From what I've read in other discussions it should be possible to pass an array without pointer decay. Yet, I need help implementing this.
Please give me a concise example of how to pass an array as a pointer of a pointer and determine it's size within the function to which it is passed.
If the array is changed in the function, I want the source of the array to be changed. And I want to minimize additional allocation of memory. And, if at all possible, I'd like to size the array within the function.
This code works without passing.
// this works
j = sizeof(hourLongs)/sizeof(hourLongs[0]);
i = 0; while (now > hourLongs[i] && i < j){i++;}
hour = --i;
This works but fails to size the array within the function.
hour = compareToLongs(&now, hourLongs, (int)(sizeof(hourLongs)/sizeof(hourLongs[0])) );
// long *, long * , int -> int
// compare time to array of times.
static int compareToLongs(long * time, long * timeList_pointer, int size){
i = 0; while (*time> (timeList_pointer)[i] && i < size){i++;}
return --i;
}
I'd like to pass the array in a way that will allow me to find it's size within the function. Something like the following, minus my errors.
hour = compareToLongs(&now, &hourLongs);
// long *, (long (*) [])* -> int
// compare time to array of times.
static int compareToLongs(long * time, long ** timeList_pointer){
int size = (int)(sizeof(*timeList_pointer)/sizeof(*timeList_pointer[0]));
i = 0; while (*time> (i < size && *timeList_pointer)[i]){i++;}
free(size);
return --i;
}
Edit: hourLongs is an array of long integers.
Edit: Regarding the title, I used the word 'reference' in the vernacular so that other barbarians like me may find the question.
Edit: I'm really looking for a way to size an array of integers within a function.
sizeof(array)
gives a some address to sizeof() that allows the size to be determined. It is that address that I would like to pass to my function.
Is there a reason why I cant pass that which is passed to sizeof() to my function?
Edit: as the operation of sizeof() suggests it is possible for an array to be passed without "pointer decay". user529758 gives three examples in this discussion
in C99 there are three fundamental cases, namely:
1. when it's the argument of the & (address-of) operator.
2. when it's the argument of the sizeof operator.
3. When it's a string literal of type char [N + 1] or a wide string literal of type wchar_t [N + 1] (N is the length of the string) which is used to initialize an array, as in char str[] = "foo"; or wchar_t wstr[] = L"foo";.
What I seek to do should be possible using &array.