MrNoFaceGuy
MrNoFaceGuy

Reputation: 3

Need help allocating memory for an struct array of arrays

So i have these structs

typedef struct user
{
  char username[30];
  char password[30];
  char email[100];
  char nome[30];


}user;
typedef struct admin
{ 
  char nome[30];
  char passwd[30];
}admin;

and i want to create these arrays with them

user database[50];
user banlist[100];
admin list[10];

how can i allocate memory for them

Upvotes: 0

Views: 48

Answers (1)

Phillipp Mevenkamp
Phillipp Mevenkamp

Reputation: 110

You already allocated memory. You did this by so called static allocation (or more specific automatic memory allocation).

If you want to allocate the memory dynamically you would have to use:

user *database = malloc(sizeof(user) * 50); 
user *banlist = malloc(sizeof(user) * 100);
admin *list = malloc(sizeof(admin) * 10);

And don't forget to free the space up, when you don't need those variables anymore.

free(database);
free(banlist);
free(list);

For more information see also: Difference between static memory allocation and dynamic memory allocation

Upvotes: 2

Related Questions