In C are there any times other than for arrays that the address-of operator is not needed? For example, I know this code needs the address of operator:
typedef struct foo_t {
int bar;
} foo_t;
void foo_init(foo_t *f) { f->bar = 123; }
... {
foo_t f;
foo_init(&f);
}
But this code will not need the address-of operator:
... {
char buffer[1024];
memset(buffer, 0, 1024);
}
Here memset
is declared as:
void *memset(void *ptr, int value, size_t num);
And in C it will auto cast that char[]
to a void*
- but trying to do the same for the foo_t
like this:
foo_t f;
memset(f, 0, sizeof(foo_t));
Won't work and will generate the expected compile-time type error. Like with the char[]
example if we use an array it will work:
foo_t list[16];
memset(foo, 0, sizeof(list));
It will again automatically cast the foo_t[]
into a void*
Is this the only time this kind of cast will happen in C? How can I know when these casts will happen?
The only “other” (see comments) case of implicit address taking I know is with function pointers [1, 2]. Given a function
int
f(void);
the following two lines have identical meaning.
int (*fptr1)(void) = f;
int (*fptr2)(void) = &f;
Both make fptr1
and fptr2
a function pointer to f
respectively.