简体   繁体   English

如何在不引用C语言结构实例的情况下访问变量?

[英]how to access a variable without referring to its structure's instance in C?

If I have a struct in C 如果我在C中有一个结构

typedef struct _a {
    int aval;
} a;

a a_inst;

void main() {
    a_inst.aval = 5;
}

how can I access "aval" without having to type as a_inst.aval for this example ?? 在此示例中,如何不必键入a_inst.aval即可访问“ aval”? Is this possible ? 这可能吗 ?

a_inst.aval refers to "the aval part of the structure a_inst ". a_inst.aval指“结构a_instaval部分”。

aval - as you want to type - would refer to " aval ...?", at which point the compiler will become grumpy and refuse to cooperate. aval您想要键入的名称将引用“ aval ...?”,这时编译器将变得脾气暴躁,拒绝合作。

Answer to your question: No. 回答您的问题:不可以。

(Unless, of course, you start wiggling about with #define / typedef / pointers as a means of shorthand notation, at which point you are crossing into dangerous waters of making your code less readable.) (当然,除非您开始使用#define / typedef /指针作为一种简写符号的方式来回扭动,否则您将陷入使代码的可读性降低的危险境地。)

Apart from #define or using a pointer, no. 除了#define或使用指针之外,否。 So you could do 所以你可以做

#define AVAL a_inst.aval

or 要么

int * pAval= a_inst.aval

But experienced programmers will not do this. 但是有经验的程序员不会这样做。

One possible way is to use a pointer on this structure field. 一种可能的方法是在此结构字段上使用指针。 But you will need 但是你需要

void main() {
  int *p_aval = &a_inst.aval;
  *p_aval=...; //access
}

personnally I will prefer to type the structure name. 就个人而言,我更喜欢键入结构名称。 It is explicit, doesn't harm (like few more characters to type) and is less prone to bugs. 它是显式的,不会造成伤害(例如,可以键入几个其他字符),并且不太容易出现错误。

Since the structure is composed by only one int you can set aval in this way: 由于结构仅由一个int组成,因此您可以通过以下方式设置aval:

*((int *) &a_inst) = 5;
printf("AVAL %d\n", a_inst.aval);

result: 结果:

AVAL 5

but i reccomend to NOT USE this kind of structure access 但我建议不要使用这种结构访问

Just presenting this as a simple, easy to understand example. 只是将其作为一个简单易懂的示例来展示。

I am assuming you want to be able to do this: 我假设您希望能够做到这一点:

typedef struct _a {
    int aval;
} a;

a a_inst;

void main() {
    aval = 5; // <-- Access aval without typing a_inst.aval
}

However, that is in no reasonable way possible. 但是,这是不可能的。

Why? 为什么?

Because what if you have: 因为如果您有:

typedef struct _a {
    int aval;
} a;

a a_inst;
a b_inst;  // Another instance of the a struct

void main() {
    aval = 5; // <-- How would the compiler know if aval refers to aval in a_inst or in b_inst?
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM