gpt4 book ai didi

c - C 中的 "Dynamic Inheritance"

转载 作者:行者123 更新时间:2023-12-03 22:23:15 25 4
gpt4 key购买 nike

我写了下面的代码并且它有效,但我想知道是否可以确保它在所有 x86 机器上一直有效。

#include <stdio.h>
#include <stdlib.h>

typedef struct Base {
int a;
float b;
} Base;

typedef struct Derived1 {
int a; // This two members have the same position as in the Base
float b;

// adding some other members to this struct
int otherMember;
int otherMember2;
} Derived1;

int main()
{
Base *bases[2];

// Filling the array with different structs
bases[0] = (Base*) malloc(sizeof(Base));
bases[1] = (Base*) malloc(sizeof(Derived1));

bases[1]->a = 5;
Derived1 *d1 = (Derived1*) bases[1];

if(d1->a == 5)
printf("SUCCESS\n");

return 0;
}

我知道为什么这个例子有效,但它总是有效吗?是否有填充或类似的东西可以阻止它工作,或者 C 标准是否支持它?

最佳答案

根据 C99 规则,这两个 struct 是不兼容的:

two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements: If one is declared with a tag, the other shall be declared with the same tag. If both are complete types, then the following additional requirements apply: there shall be a one-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types, and such that if one member of a corresponding pair is declared with a name, the other member is declared with the same name. For two structures, corresponding members shall be declared in the same order.

您的代码打破了成员之间的一对一对应关系,因此根据标准,这将是无效的:

Base *d1 = (Base*) bases[1];
d1->a=5; // Not valid

幸运的是,您可以通过将 Base 嵌入到 Derived1 中轻松使其有效:

typedef struct Derived1 {
Base base;
// adding some other members to this struct
int otherMember;
int otherMember2;
} Derived1;

根据 C99,

A pointer to a structure object, suitably converted, points to its initial member

因此,这是有效的:

Base *d1 = (Base*) bases[1];
d1->a=5; // Valid

注意: This Q&A谈论严格别名的相关主题。

关于c - C 中的 "Dynamic Inheritance",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42822234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com