Skip to content

Instantly share code, notes, and snippets.

@pavly-gerges
Created October 29, 2022 14:23
Show Gist options
  • Save pavly-gerges/e528c0543cbd1b6246b750a6ea56d7b2 to your computer and use it in GitHub Desktop.
Save pavly-gerges/e528c0543cbd1b6246b750a6ea56d7b2 to your computer and use it in GitHub Desktop.
An example of dynamic arrays in C
/**
* @brief: Shows a minimalistic example of dynamic arrays.
*
* @author pavl_g.
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
const char* username;
const char* password;
} User;
static inline User* getUserFromCredentials(const char* username, const char* password) {
User* user = (User*) calloc(1, sizeof(User));
user->username = username;
user->password = password;
return user;
}
static inline void addUser(User** users, User* user, int index) {
users[index] = user; // jump to a new user
}
int main() {
void** users = (void**) calloc(1, sizeof(void*));
User* bishoy = getUserFromCredentials("Bishoy", "BPass");
User* pavly = getUserFromCredentials("Pavly", "PPass");
addUser(users, bishoy, 0);
addUser(users, pavly, 1);
printf("%s \n", ((User*) users[0])->username);
printf("%s \n", ((User*) users[1])->username);
printf("%s \n", ((User*) users[0])->password);
printf("%s \n", ((User*) users[1])->password);
return 0;
}
@pavly-gerges
Copy link
Author

Output:

Bishoy 
Pavly 
BPass 
PPass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment