简体   繁体   English

如果用指针初始化结构,它本身的名称是什么

[英]If Initialize the struct with the pointer what is its name itself

If consider two following methods to introduce the struct:如果考虑以下两种方法来引入结构:

struct example {
  int foo;
};
int main() {
  struct example e;
  e.foo=1;
}

and

struct example {
  int foo;
};
int main() {
  struct example *e=malloc(sizeof(struct example));
  e->foo=1;
}

Both are correct.... In the first case I declare the struct:两者都是正确的......在第一种情况下,我声明了结构:

struct example {
  int foo;
};

and initialize its instance with the name e by并用名称e初始化其实例

  struct example e;

However in the second example I initialize the struct through creating the pointer *e and assigning it an addressee from heap with the help of malloc - OK.然而,在第二个示例中,我通过创建指针*e并在 malloc 的帮助下从堆中为其分配地址来初始化结构 - 好的。

But what is the name of my initialized instance of the struct example itself in the second example?但是在第二个示例中,我初始化的struct example本身的名称是什么? I may initialize many struct example instances (through pointers) for example:我可能会初始化许多struct example实例(通过指针),例如:

struct example *ptr1=malloc(sizeof(struct example));
struct example *ptr2=malloc(sizeof(struct example));
.
.
.
struct example *ptr100=malloc(sizeof(struct example));

But what are the individual names of these instances?但是这些实例的个别名称是什么?

No instance has a name.没有实例有名称。 We give names to variables, to express algorithms, formulas, but this name is not part of the data itself.我们给变量命名,以表达算法、公式,但这个名字不是数据本身的一部分。

In your case, each instance is only made of an integer, and is located in a specific place (stack or heap) but there is no name around.在您的情况下,每个实例仅由 integer 组成,并且位于特定位置(堆栈或堆),但周围没有名称。

The names only exist in the source code but disappear at compile time (except when explicitly collected for debugging purpose).这些名称仅存在于源代码中,但在编译时会消失(除非出于调试目的而明确收集)。

In your example there is not any name, name is attribute of a variable and not a memory.在您的示例中,没有任何名称,名称是变量的属性,而不是 memory。 But you could name the structure with some name and create name attribute inside this structure for example:但是您可以使用一些名称命名结构并在此结构中创建名称属性,例如:

struct example {
  int foo;
  char[80] name;
};

And then set individual name for each structure if you need.如果需要,然后为每个结构设置单独的名称。

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

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