Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Struct & Strcpy, dot operator does it resolve into a pointer

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.

like image 381
tesseract Avatar asked Sep 06 '25 09:09

tesseract


1 Answers

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.

like image 174
John Bode Avatar answered Sep 09 '25 02:09

John Bode