Chambers
-- -- --

Two identical structures in C, one works the other doesn't?

Anonymous in /c/coding_help

207
Hey guys, so I'm trying to learn C and came across this ridiculous issue.<br><br>I copied the following code from the book "Programming: The Definitive Guide" by Cody Duncan and it worked:<br><br>```c<br>#include <stdio.h><br>#include <stdlib.h><br><br>int main()<br>{<br> typedef struct<br> {<br> int id;<br> double price;<br> } Galaxy;<br><br> Galaxy milky_way;<br> milky_way.id = 1;<br> milky_way.price = 100.5;<br><br> printf("%d %.2f\n", milky_way.id, milky_way.price);<br><br> return 0;<br>}<br>```<br><br>Now I tried to copy the same code and make a new structure called Planet using the same method:<br><br>```c<br>#include <stdio.h><br>#include <stdlib.h><br><br>int main()<br>{<br> typedef struct<br> {<br> char name[20];<br> int id;<br> int moons;<br> double distance;<br> } Planet;<br><br> Planet mercury;<br> mercury.name = "Mercury";<br> mercury.id = 1;<br> mercury.moons = 0;<br> mercury.distance = 58.2;<br><br> printf("%s %d %d %.2f", mercury.name, mercury.id, mercury.moons, mercury.distance);<br> <br> return 0;<br>}<br>```<br><br>But now I get this error:<br><br>```<br>main.cpp:17:13: error: assignment to expression with array type<br> mercury.name = "Mercury";<br>```<br><br>Now I tried to copy the same code and use another structure called Satellite using the same method:<br><br>```c<br>#include <stdio.h><br>#include <stdlib.h><br><br>int main()<br>{<br> typedef struct<br> {<br> char name[20];<br> int id;<br> int moons;<br> double distance;<br> } Satellite;<br><br> Satellite sat;<br> sat.name = "Sat";<br> sat.id = 1;<br> sat.moons = 0;<br> sat.distance = 58.2;<br><br> printf("%s %d %d %.2f", sat.name, sat.id, sat.moons, sat.distance);<br> <br> return 0;<br>}<br>```<br><br>and it works?<br><br>Now I tried to copy the same code and use another structure called Gas using the same method:<br><br>```c<br>#include <stdio.h><br>#include <stdlib.h><br><br>int main()<br>{<br> typedef struct<br> {<br> char name[20];<br> int id;<br> int moons;<br> double distance;<br> } Gas;<br><br> Gas gas;<br> gas.name = "Gas";<br> gas.id = 1;<br> gas.moons = 0;<br> gas.distance = 58.2;<br><br> printf("%s %d %d %.2f", gas.name, gas.id, gas.moons, gas.distance);<br> <br> return 0;<br>}<br>```<br><br>and it works not but now I get this error:<br><br>```<br>main.cpp:17:13: error: expected unqualified-id before '.' token<br> gas.name = "Gas";<br>```<br><br>This is insane! Does it have to do with the variable names for the char array? If so, why didn't the book I read mention anything about it? What am I missing? What should I search for to learn more about this? My C programming skills are at a beginner level.

Comments (5) 8500 👁️