Why does a char array need strcpy and char star do

2019-07-20 10:59发布

问题:

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?

回答1:

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).



回答2:

Because the location of an array is fixed, while the value of a pointer (which is itself a location) is not. You can assign new values to a pointer, but not an array.

Under the hood, they're both the same thing; an array name in C is a pointer, but from a semantics point of view you cannot reassign an array but you can repoint a pointer.



回答3:

When you write

a.name = "eaaa" ;

the compiler will allocate memory for a NULL terminated string eaaa\0 and, because of that instruction, it will make the pointer name point to that location (e.g. the name variable will contain the address of the memory location where the first byte of the string resides).

If you have the array instead, you already have an allocated area of memory (which cannot be assigned to another memory location!), and you can only fill it with data (in this case bytes representing your string).



回答4:

This is my understanding about what might be the reason for this.

I think it's about the way that language works. C (and also C++) produces an unmanaged code - which means they don't need an environment (like JVM) to run on to manage memory, threading etc. So, the code is produced to an executable that is run by the OS directly. For that reason, the executable includes information, for example, how much space that to be allocated for each type (not sure for the dynamic types though) including the arrays. (This is also why C++ introduced header files since this was the only way to know size of an object during compilation)

So, when the compiler sees an array of characters, it calculates how much space is needed for it during the compilation phase and put that information into the executable. When running the program, the flow can figure out how much space is required and allocates that much of memory. If you change this multiple times, let's say in a C function, each assignment would make the previous one(s) invalid. So, IMO, that's why the compiler doesn't allow that.