Created
October 29, 2022 14:23
-
-
Save pavly-gerges/e528c0543cbd1b6246b750a6ea56d7b2 to your computer and use it in GitHub Desktop.
An example of dynamic arrays in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: