Passing in Arrays to Functions
suggest changeint getListOfFriends(size_t size, int friend_indexes[]) {
size_t i = 0;
for (; i < size; i++) {
friend_indexes[i] = i;
}
}
/* Type "void" and VLAs ("int friend_indexes[static size]") require C99 at least.
In C11 VLAs are optional. */
void getListOfFriends(size_t size, int friend_indexes[static size]) {
size_t i = 0;
for (; i < size; i++) {
friend_indexes[i] = 1;
}
}
Here the static
inside the []
of the function parameter, request that the argument array must have at least as many elements as are specified (i.e. size
elements). To be able to use that feature we have to ensure that the size
parameter comes before the array parameter in the list.
Use getListOfFriends()
like this:
#define LIST_SIZE (50)
int main(void) {
size_t size_of_list = LIST_SIZE;
int friends_indexes[size_of_list];
getListOfFriends(size_of_list, friend_indexes); /* friend_indexes decays to a pointer to the
address of its 1st element:
&friend_indexes[0] */
/* Here friend_indexes carries: {0, 1, 2, ..., 49}; */
return 0;
}
See also
http://stackoverflow.com/documentation/c/322/arrays/22905/passing-multidimensional-arrays-to-a-function#t=201701141221030574016
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents