Why can't we directly assign strings using assignment operator (=) and we have to switch for strcpy (from string.h)? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why can't we directly assign strings using assignment operator (=) and we have to switch for strcpy (from string.h)?

the link to code is as follows: https://code.sololearn.com/cRFqD5BUTbpc I know the error message is displayed as ./Playground/file0.c: In function 'main': ./Playground/file0.c:17:13: error: assignment to expression with array type 17 | cs2.title = "Advanced C++"; | ^

14th Nov 2020, 6:07 AM
Mayur Chittaragi
Mayur Chittaragi - avatar
6 Answers
+ 3
Here's your answer: https://stackoverflow.com/questions/3473765/string-literal-in-c?lq=1#:~:text=You%20cannot%20assign%20a%20string,at%20the%20time%20of%20definition.&text=char%20a%5B%5D%20%3D%20%22something%22,the%20string%20to%20the%20array. Also from the best answer to this question https://stackoverflow.com/questions/8040284/why-is-literal-string-assignment-in-c-not-possible-for-array-with-specified-leng You are telling the compiler to copy the contents of one string over to another one. This is not a simple operation. In the case of char a[] = "test"; it was rather simple because it was just 5 pushes on the stack. In this case however it is a loop that needs to copy 1 by 1. If you are not satisfied, you can look for more similar questions on stack overflow
14th Nov 2020, 8:23 AM
Davide
Davide - avatar
+ 4
LastSecond959 It's been 3 days, I can't remember the original title fully. I prefer to view a code than making assumptions on what or why, that is why I suggest people to attach code whenever possible.
17th Nov 2020, 7:56 AM
Ipang
+ 2
Please attach your code link in thread's Description for inspection, without a closer look, anyone can only play a guessing game.
14th Nov 2020, 7:08 AM
Ipang
+ 1
Ipang Even without it, the question is detailed enough.
17th Nov 2020, 7:46 AM
LastSecond959
LastSecond959 - avatar
+ 1
LastSecond959 Code link is added later on, and the thread didn't look as it is now in the time when I suggested a link to code.
17th Nov 2020, 7:49 AM
Ipang
+ 1
Ipang I'm talking about the title (not the attachment), is it edited?
17th Nov 2020, 7:51 AM
LastSecond959
LastSecond959 - avatar