I am reviewing someone's code and the developer has assigned one struct to another. The struct contains a char array. Somehow that "works", meaning the char array from struct A does get copied to struct B (not by reference). I'm totally baffled. Can s.o. explain that to me? I have written up a little program to illustrate the "problem".
#include <stdio.h>
#include <string.h>
/**************************************
* some define and typedef for later
**************************************/
#define MAX_LEN (80)
typedef struct month_s
{
char name[MAX_LEN];
} month_st;
/**************************************
* This bit is clear.
**************************************/
static void usingString()
{
char mCur[MAX_LEN] = {"Jan"};
char mNext[MAX_LEN] = {"Feb"};
/** this doesn't compile (of course) */
//mCur = mNext;
/** we need a pointer/reference */
char *pmCur = &mCur[0];
/** however now we "copy by reference"...*/
pmCur = &(mNext[0]);
/** ...so this change also applies to pmCur*/
strcpy(mNext, "Mar");
/** ...so pmCur is now "Mar"*/
printf("%s: %s\n", __func__, pmCur);
}
/**************************************
* I though the same/s.th. similar
* as above happens here. But this "works".
* I'm surprised to see that not to be
* the case. Can someone explain?
**************************************/
static void usingStruct()
{
month_st mCur = {"Jan"};
month_st mNext = {"Feb"};
/** I would have thought this is "copy by reference" for the string! */
mCur = mNext;
/** I would have thought this also overrides mCur.name
'cause it's pointing to mNext.name now */
strcpy(mNext.name, "Mar");
/** how come this works??? mCur.name is still "Feb"*/
printf("%s: %s\n", __func__, mCur.name);
}
/**************************************
* just the main()
**************************************/
int main()
{
usingString();
usingStruct();
return 0;
}
I see three explanations about the difference between pointers and arrays, but they don't seem to address the question being asked, as I understand it.
The question, as I understand it, is: "I know that I can't assign one array to another, so why can I do it if the array is inside a struct?"
The answer is, basically, "because the language said so". Even though a struct is an aggregate type, and may very well contain an array, the language spec says that structs are assignable, and therefore structs are assignable. This is section 6.5.16.1 Simple assignment
in both N1256 and N1570.
(Under the hood, the compiler may have to implement a memory copy, but that's the compiler's problem, not yours.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With