I made a simple program in C to check if two words are anagrams. My question is that if I\'m passing word_one and word_two as parameters, doesn\'t that mean that I\'m not modify
Except when it is the operand of the sizeof
or unary &
operator, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T
" will be converted ("decay") to an expression of type "pointer to T
", and the value of the expression will be the address of the first element of the array.
When you call
read_word(word_one);
The expression word_one
is converted from type "26-element array of int
" to "pointer to int
", so what actually gets passed to read_word
is the address of the first element of word_one
.
In the context of a function parameter declaration, T a[N]
and T a[]
are both interpreted as T *a
- a
is declared as a pointer to T
, not an array of T
. Thus, the prototype
void read_word(int counts[26])
is interpreted as
void read_word(int *counts)
Thus, read_word
does indeed modify the contents of word_one
and word_two
.
You'll want to pass the size of the array as a separate parameter:
read_word( word_one, sizeof word_one );
...
void read_word( int *counts, size_t size )
{
...
}
since you won't know how big the target array is from the pointer alone.