suppose i have something like this
typedef char string[21]
struct planet_s
{
string name,orbits;
float distance;
string discoverer;
int yeardiscovered;
}one_planet;
next i need to initialize some information about the planet therefore my text book says
strcpy(one_planet.name, "Earth"); ?confused with these
strcpy(one_planet.orbits, "Sun"); ?
one_planet.distance = 150;
one_planet.mass = 6.00e+24;
strcpy(one_planet.discoverer, "me"); ?
one_planet.yeardiscovered = 1000;
my Confusion arises in the strcpy
,let me put things in point form
Strcpy
needs a pointer to a string as its first argument
does one_planet.name
resolve into a pointer to the strcuts name array(does the dot operator resolve into an address)?
how come one_planet.distance =150
does not resolve into an address since we are assign it its value straight away? this is what i been taught, one_planet.distance directly access the struct element and assigns it. my confusion is with the strcpy, since it needs an address to store a string?
hope you understand where my confusion comes form thanks.
Except when it is the operand of the sizeof
or unary &
operator, or when it is a string literal being used to initialize another 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 in the array.
In the line
strcpy(one_planet.name, "Earth");
the expression one_planet.name
has type "21-element array of char
"; since the expression is not the operand of the sizeof
or unary &
operators, it is converted to an expression of type "pointer to char
", and the address of the first element of the array is passed to strcpy
.
The .
operator doesn't make a difference in this case; what matters is the type of the member, regardless of how that member is accessed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With