将结构体A赋值给B,其中A的元素是B的子集



据我所知,分配数组是内存复制操作,这会起作用吗?

struct x{
    int i;
    int j;
} A[5];
struct y{
    int i;
    int j;
    struct y * next;
} B[5];

那么我可以这样做:

B[0] = A[0];

和期望I和j复制索引[0]?

编辑:我真正想知道的是如何使这个工作在c。

我的建议是在struct y中嵌入struct x,像这样:

struct x{
    int i;
    int j;
} A[5];
struct y{
    struct x x;
    struct y * next;
} B[5];

这样,很容易赋值,并且两个结构体的第一个sizeof(struct x)字节的内存布局保证是相同的,即使在C89中也是如此。

你现在可以做

B[0].x = A[0];

由于struct x保证出现在内存中struct y的第一个字节,您仍然可以执行

memcpy(&B[0], &A[0], sizeof A[0]);

你可以在http://codepad.org/2rCJA0cx

不行,那行代码无法编译。

见http://codepad.org/6g3c9Ctz

您可以使用memcpy使其工作。见http://codepad.org/1I9Z3npC

#include <string.h>
#include <stdio.h>
struct x{
    int i;
    int j;
} A[5];
struct y{
    int i;
    int j;
    struct y * next;
} B[5];
int main() {
    A[0].i = 5;
    A[0].j = 7;
    memcpy(&B[0], &A[0], sizeof A[0]);
    printf("%d %dn", B[0].i, B[0].j);
    return 0;
}

不能,因为结构体x和结构体y不是兼容的类型。

可以使用强制转换:

(struct x)(B[0]) = A[0];

最新更新