Passing in Arrays to Functions
suggest changevoid getListOfFriends(size_t size, int friend_indexes[]) {
size_t i = 0;
for (; i < size; i++) {
friend_indexes[i] = i;
}
}
/* [static size] requires C99. When size is not a constant expression this is a
variably modified type, so C11 makes it optional along with VLAs. The static
keyword promises at least size elements and a non-null argument. */
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 requests that the argument point to at least size elements. The size parameter has to come before the array parameter so that it is in scope. Passing a null pointer or a shorter array for that parameter is undefined behavior.
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, friends_indexes); /* friends_indexes decays to a pointer to its
first element, &friends_indexes[0]. */
/* The [static size] version stores 1 in every element. */
return 0;
}
See also
See also Passing multidimensional arrays to a function.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents