John Paul II (no******@the.vatican) wrote:
typedef struct __Y
That is an identifier which you are not allowed to use. Identifiers
starting with __, or with _ and a capital letter, are reserved for the
implementation; and under many circumstances, ones starting with _ and
anything else as well. Besides, you don't even need the tag here if
you're going to refer to it by a typedef name anyway. Dike it out.
{
int a;
char b[5];
} Y;
Y my_struct;
Y *my_ptr_struct;
void my_func (char *str);
main
This should not have compiled. Please copy & paste, don't re-type, code
you are asking about. That way you won't introduce typos.
{
my_ptr_struct = &my_struct;
my_func(&my_struct.b);
my_func(&my_ptr_struct->b);
}
Both func calls gave me compiler warnings of pointer mismatch. So I
changed to (char *) &my_struct.b and (char *) &my_ptr_struct.b. Is
this correct passing of pointers to members?
No. In fact, your question has nothing to do with struct members as
such. The problem lies with getting the address to an array, regardless
of whether it is a struct member. Try, for example, this code:
void my_func (char *str);
int main(void)
{
char my_array[5];
my_func(&my_array);
}
You should get a very similar warning.
Casting the pointer to char * is the wrong solution. In fact, casting
away warnings is very nearly always the wrong solution. In this case,
the right solution is to pass the right address: a pointer to the first
member of mystruct.b, rather than to the entire array. So you want:
my_func(&(*my_struct.b));
or, equivalently,
my_func(&(my_ptr_struct->b[0]));
Richard