使用“=”在内部分配带有 char 数组的结构有效吗?

Aud*_*oid 5 c arrays struct char

我正在审查某人的代码,开发人员已将一个结构分配给另一个结构。该结构包含一个 char 数组。不知何故,这“有效”,这意味着结构体 A 中的 char 数组确实被复制到结构体 B (不是通过引用)。我完全困惑了。可以给我解释一下吗?我写了一个小程序来说明这个“问题”。

#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;
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ame 4

我看到了关于指针和数组之间差异的三种解释,但据我所知,它们似乎没有解决所提出的问题。

据我了解,问题是:“我知道我不能将一个数组分配给另一个数组,那么如果数组位于结构内部,为什么我可以这样做呢?”

答案基本上是“因为语言是这么说的”。尽管结构是聚合类型,并且很可能包含数组,但语言规范表示结构是可分配的,因此结构是可分配的。这是N1256N15706.5.16.1 Simple assignment中的部分。

(在幕后,编译器可能必须实现内存复制,但这是编译器的问题,而不是你的问题。)