Does structure copy can handle char array too in c? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Does structure copy can handle char array too in c?

code snip>> #include <stdio.h> #include <string.h> typedef struct ST { char a[50]; }s; int main() { s s1,s2; strcpy (s1.a,"Saga"); s2 = s1; printf("%s",s2.a); return 0; } output: Saga How structure copy works internally? Is it behave same in cpp? someone please explain it.

27th May 2018, 7:36 AM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar
6 Answers
+ 1
memcpy() is part of a C library, so no. what C uses when you do so is equivalent to a malloc
2nd Jun 2018, 8:05 PM
๐Ÿ™evil octopus
๐Ÿ™evil octopus - avatar
+ 2
It is equivalent to a memcpy. When you do the "=", your computer will blindly copy all bits from one memory location to the other one.
3rd Jun 2018, 7:56 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
it works the same as with every other variable copy. e.g.: int a, b; a = 2; b = a; //now b is also 2 what really happens here is: 1. memory spaces for 'a' and 'b' are created 2. the value 2 is assigned to the memory space assigned to 'a' 3. a copy of 'a' is created and stored somewhere in an available spot in memory 4. the copy made in step 3 is assigned to the spot in memory assigned to 'b' 5. the spot in memory for the copy created is cleared in order to free up memory so when you say 's2 = s1', a copy of 's1' is created and stored somewhere and then copied onto 's2' and then deleted to free up memory.
2nd Jun 2018, 7:51 PM
๐Ÿ™evil octopus
๐Ÿ™evil octopus - avatar
+ 1
it's what Baptiste E. Prunier explained. a memcpy() is just a way to copy all bits from one memory address to another, but your OS does not use memcpy() to do so. the method it uses achieves the same purpose, though.
3rd Jun 2018, 10:06 AM
๐Ÿ™evil octopus
๐Ÿ™evil octopus - avatar
0
๐Ÿ™evil octopus Does it mean os internally follows memcopy for this?
2nd Jun 2018, 7:55 PM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar
0
๐Ÿ™evil octopus Your answer is not clear. Could you please clarify?
3rd Jun 2018, 8:38 AM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar