In a C function prototype, char ARR[]
is really just syntactic sugar for char *
because a function call converts an array into a pointer to the first element of the array. So sizeof(ARR)
will have the same value as sizeof(char *)
. You need to pass the actual length as a separate parameter.
If randint(n)
returns a number from 1 to n, be aware that array index operations in C start from index 0, not index 1, so you would need to subtract 1 from the return value of randint(n)
to get an index in the range 0 to n-1.
Your rand_word
function takes a pointer to the first element of an array of char
and returns a single element of the array (a single char
) converted to an int
. But your caller passes the function a pointer to the first element of an array of const char *
and expects it to return a const char *
(judging from the use of the "%s"
printf
format specifier).
Putting that altogether, your rand_word
function should look something like this:
const char *rand_word(int n, const char *ARR[])
{
int r = randint(n) - 1; // randint returns number in range 1 to n
return ARR[r];
}
Since your WORDS
array has 3 elements, your printf
call should be something like:
printf("%s", rand_word(3, WORDS));
You could also use this macro to get the length of an array (doesn't work on pointers):
#define ARRAY_LEN(ARR) (sizeof (ARR) / sizeof (ARR)[0])
Then your printf
call can be something like this:
printf("%s", rand_word(ARRAY_LEN(WORDS), WORDS));