Click here to Skip to main content
15,884,537 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
struct data 
{
 char name[80];
 double age;
}
 const data MyStruct = {"a",1000};
 strcpy(MyStruct.name,"p");
 printf(MyStruct.name);

Please explain if this code has any problem. Or is it okay? Than why?
Posted
Updated 30-Mar-11 11:35am
v3
Comments
HimanshuJoshi 30-Mar-11 17:36pm    
Edited to remove bold tag in text. Have you tried running it? Have you faced any problem?

besides the problems that SA pointed out, from looking at what that code is doing, its conceptually wrong... you've declared a constant structure then you're trying to copy a different string onto your character buffer after the fact.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 31-Mar-11 3:05am    
Of course. My 5.
Please see a comment by Niklas to my Answer -- an interview re-post. Very unpleasant. I feel bad about it: wasn't worth answering...
--SA
Well, it's not a perfect style because of 4 immediate constants hard-coded. It also consumes 80 bytes of memory without purpose, but this is because of the nature of static array. To me, null terminated string was one of the worst ideas in the history of technology, but this is not your fault :-). You could use std::string instead.

The function strcpy is unsafe, better use strcpy_s.
After the structure declaration you need ';'.
The code will not compile because of const before data.

Now, may I understand why are you asking such Question if your code does not even compile, and you even did not report this problem? Did you even try to compile it?
It looks like you're trying to put too much of your job on others, but it does not help you much.

I must say, your method of learning is not effective. I advice you stop asking such Questions here at CodeProject and learn the basics using some good manual and exercises, using the approach I outlined here:
I have a problem with my program. Please help![^].

—SA
 
Share this answer
 
v2
Comments
Niklas L 31-Mar-11 2:59am    
It's from homework, or a job interview, and yet another repost of http://www.codeproject.com/Questions/174563/Basic-of-C-and-Cplusplus-quiz-Questions.aspx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900