如何在C中动态添加结构成员? [英] How to add a structure member dynamically in C?
问题描述
struct point {
int x;
int y;
};
main() {
struct point a;
a.x = 5;
a.y = 10;
printf("%d %d", a.x, a.y);
}
输出:
5 10
这里如果我想动态添加一个成员 (int z
) int 相同的结构.流程是怎样的?
Here if I want add a member (int z
) int the same structure dynamically.
What is the procedure?
我尝试过的:
struct point {
int x;
int y;
};
struct newpoint {
struct point a;
int z;
};
我已经尝试了上述步骤,通过这些步骤,我们添加了一个新成员和旧结构point
到新结构newpoint
.但这不是我想要的,我想动态添加新成员相同的结构.我在一次采访中得到了这个问题.
I have tried the above steps, through which we have added a new member and the old structure point
to new structure newpoint
. But this is not what I want, I want to add the new member the same structure dynamically. I got this question in an interview.
推荐答案
问你这个问题的面试官让你落入陷阱.
The interviewer that asked you this has set you on a trap.
在 C 中动态定义结构"是不可能的.可以在其他语言中进行鸭子类型",例如 JavaScript,但 C 结构是编译时定义,并且是静态的.
It's impossible to "dynamically define a struct" in C. It's possible to do "duck-typing in other languages, for example JavaScript, but C structures are compile time definitions and are as static as it gets.
这篇关于如何在C中动态添加结构成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!