简体   繁体   中英

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

  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.

But what is the name of my initialized instance of the struct example itself in the second example? I may initialize many struct example instances (through pointers) for 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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