[英]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);
}
Output: 输出:
5 10
Here if I want add a member ( int z
) int the same structure dynamically. 这里,如果我想动态地添加一个成员(
int z
)int相同的结构。 What is the procedure? 程序是什么?
What I have tried: 我尝试过的:
struct point {
int x;
int y;
};
struct newpoint {
struct point a;
int z;
};
I have tried the above steps, through which we have added a new member and the old structure point
to new structure newpoint
. 我已经尝试了上面的步骤,通过这些步骤我们添加了一个新成员和旧结构
point
新结构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. 问你的面试官让你陷入困境。
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中“动态定义结构”是不可能的。可以在其他语言中进行“鸭子打字”,例如JavaScript,但C结构是编译时定义,并且是静态的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.