"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > In C and C++, why can't arrays be assigned directly, but in structures, it is OK?

In C and C++, why can't arrays be assigned directly, but in structures, it is OK?

Posted on 2025-04-18
Browse:476

Why Can't I Directly Assign Arrays in C and C  , But I Can Within Structs?

Array Assignment in C and C

C and C allow memberwise assignment of arrays within structs but not in general. This behavior is a result of the historical evolution of the languages.

Initially, arrays in C were modeled as pointers in memory, known as a "cooked arrays." When structures were introduced, arrays within structures were treated differently to ensure memory safety. This allowed arrays to be assigned memberwise within structs without compromising compatibility with existing code.

In contrast, assignment of arrays outside of structs was not supported in C's original design. This was due to concerns about pointer rebasing and the lack of size information for arrays declared as function parameters. To avoid introducing bugs and compatibility issues, explicit assignment using memcpy was preferred.

However, as noted by Luther Blissett, C's specification regarding structure assignment explicitly allows memberwise assignment of contained arrays. This was an unintended side effect of the design, but it was embraced as a way to facilitate data copying within structs without breaking established patterns.

Therefore, the support for memberwise assignment of arrays within structs but not generally is a legacy of C's early design decisions and the subsequent evolution of the language, resulting in a distinction between arrays embedded within structures and arrays used independently.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3