I have many functions like:
void write(char* param, int len)
{
//
}
And I notice that I almost never use the & operator for arguments. When I pass an array:
char in[20];
write(in, 20);
I dont need it, but when I pass a single value:
write(5, 1);
I don’t seem to need it, and when I pass a pointer:
char* in = malloc(20);
write(in, 20);
I also dont need it. So in which circumstances do I actually need to call:
write(&in, 1);
Because I’m confused 😀
In practice, integer types may be converted to pointers implicitly by the compiler. In theory, this is illegal and compilers that accept it will usually issue a warning:
In your above example:
charis an integer type, so if your compiler allows it, it may be implicitly converted to a pointer type, although it is not part of the C standard and is completely compiler-specific.Note that converting an integer type to a pointer type using a cast is allowed by the standard, although results are implementation-defined:
The only allowed case of implicit conversion is when integer constant
0, which denotes a null pointer:Note that the integer constant is itself allowed, but a variable of integer type with the value
0is not:As for the others, when you pass a pointer, you don’t need the
&, obviously, because it’s already a pointer. When you pass an array, it decays to a pointer so you don’t need&there either. In both these cases it would be actually illegal to use it, as your function above expects achar *and be fed with achar **and achar (*)[20]respectively.