Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a char array need strcpy and char star doesn't - using structs in C

I have a misunderstanding regarding this code -

typedef struct _EXP{
    int x;
    char* name;
    char lastName[40];
 }XMP

...main...
XMP a;
a.name = "eaaa";
a.lastName = strcpy(a.lastName, "bbb");

Why can't I use: a.lastName = "bbbb"; and that's all?

like image 486
user1386966 Avatar asked Jan 25 '26 01:01

user1386966


1 Answers

Well consider the types here. The array has the contents of the string, while the char* merely points to the data. Consequently the array requires strcpy and friends.

Besides, if you allocated memory for the char* on the heap or stack and then wanted to assign some content to that, you'd also have to use strcpy because a mere assignment would create a dangling pointer (i.e. a memory leak).

like image 131
0xC0000022L Avatar answered Jan 27 '26 21:01

0xC0000022L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!