How to access a data structure created in one func

2019-08-27 19:17发布

问题:

If I could, I'd just fix this by initializing a copy of the structure in the main function and passing that in to the other function, but I'm not allowed to change the function headers for this project.

Since I'm given this to work with, I'm also sure there's an equally good solution that'll help me learn something about how dynamic memory allocation can be used to make a function's actions last independently of the scope of that function.

My struct:

typedef struct AmNet { // this struct can be changed as needed
   int size;
   User ** users; // group of users in the net
   User *front; // the first user
   User *back; // the last user
} *AmNet;

The function to create is:

void create_net(){ // this line cannot be changed
}

In the main function in another file, called simply with:

create_net();

Then, for example -- this function should be able to access the structure, create a new User, and add it to the same structure's list of users.

void addUser( const char *name ) {
}

And the other functions within the same .c file as the struct initialization also don't take the data structure or return it, but they can access it and act upon it. It's as if the structure should be able to be treated like a global variable.

How can this be accomplished?

回答1:

To declare a global variable, put the declaration outside all functions.

struct AmNet gNet;

void create_net() {
   gNet.front = NULL;
   ...
}

Global variables like gNet are widely considered bad practice. I can see no other way if you cannot change the prototype, but a static declaration will at least keep it in file scope.

/* in AmNet.c */
static struct AmNet *gNet;

void create_net() {
  gNet = (struct AmNet *)malloc(sizeof(struct AmNet));
  gNet->front = NULL;
 ...
}