Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* structlist.c
- * A testing program for managing an array containing structure pointers. */
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define MAX_STRUCT_COUNT 5
- #define MAX_ITERATION_COUNT 10
- typedef struct {
- int x;
- int y;
- int index;
- } test_struct_t;
- test_struct_t* struct_list[MAX_STRUCT_COUNT];
- test_struct_t* add_struct(int x, int y) {
- // find the next free position in the array
- for (int i = 0; i < MAX_STRUCT_COUNT; i++) {
- if (struct_list[i] == NULL) {
- if ((struct_list[i] = malloc(sizeof(test_struct_t))) == NULL) {
- return NULL;
- }
- struct_list[i]->x = x;
- struct_list[i]->y = y;
- struct_list[i]->index = i;
- return struct_list[i];
- }
- }
- return NULL;
- }
- void remove_struct(test_struct_t* target) {
- struct_list[target->index] = NULL;
- free(target);
- }
- int main(void) {
- int valid_structs = 0;
- int max_iterations = (MAX_ITERATION_COUNT > 255) ? 255 : MAX_ITERATION_COUNT;
- // register structs
- for (int i = 0; i < max_iterations && valid_structs < MAX_STRUCT_COUNT; i++) {
- printf("Iteration %d: ", i + 1);
- if (!add_struct(i, i + 4)) {
- printf("Could not create struct; skipping...\n");
- struct_list[i] = NULL;
- continue;
- }
- printf("Created struct at pos. %d with X = %d and Y = %d\n", struct_list[valid_structs]->index, struct_list[valid_structs]->x, struct_list[valid_structs]->y);
- valid_structs++;
- }
- if (valid_structs < 1) {
- fprintf(stderr, "No structs could be created... exiting\n");
- return 1;
- }
- // testing (free a random one)
- printf("\nSuccessfully created %d structs (max iteration count of %d).\n\nFreeing a random one...\n", valid_structs, max_iterations);
- srand(time(NULL));
- int target;
- while (struct_list[target = rand() % MAX_STRUCT_COUNT] == NULL);
- printf("Removing struct at pos. %d: %p (x = %d, y = %d)\n", target, struct_list[target], struct_list[target]->x, struct_list[target]->y);
- remove_struct(struct_list[target]);
- printf("Removed struct at pos. %d\nProof: struct_list[%d] = %p\n", target, target, struct_list[target]);
- // auto-cleanup
- for (int i = 0; i < MAX_STRUCT_COUNT; i++) {
- if (struct_list[i] != NULL) {
- remove_struct(struct_list[i]);
- }
- }
- printf("\nAll other structs cleaned.\nExiting...\n\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement