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;
}