1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMBER_OF_ELEMENTS 10
#define MAX_STRING_LENGTH 256
typedef struct
{
char * field;
} my_struct;
int main()
{
// Allocate memory for strings
char **strings = malloc(NUMBER_OF_ELEMENTS * sizeof(char *));
assert(strings != NULL);
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
strings[i] = malloc(MAX_STRING_LENGTH);
assert(strings[i] != NULL);
}
// Fill with text
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
int result = snprintf(strings[i], MAX_STRING_LENGTH, "This is string number %d", i);
assert(result > 0);
}
// Show strings
puts("--- Show strings");
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
printf("%d: %s\n", i, strings[i]);
}
puts("------------------------------------");
// Allocate memory for structs
my_struct *structs = malloc(NUMBER_OF_ELEMENTS * sizeof(my_struct));
assert(structs != NULL);
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
structs[i].field = malloc(MAX_STRING_LENGTH);
assert(structs[i].field != NULL);
}
// Fill with text
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if(i == 2 || i == 4 || i == NUMBER_OF_ELEMENTS -1)
{
// Common texts
int result = snprintf(structs[i].field, MAX_STRING_LENGTH, "This is string number %d", i);
assert(result > 0);
}
else
{
// Different texts
int result = snprintf(structs[i].field, MAX_STRING_LENGTH, "This is struct number %d", i);
assert(result > 0);
}
}
// Show strings
puts("--- Show structs");
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
printf("%d: %s\n", i, structs[i].field);
}
puts("------------------------------------");
// Compare
puts("--- Compare elements");
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
int cmp = strcmp(strings[i], structs[i].field);
printf("%dth elements are %sequal\n", i, cmp == 0 ? "" : "NOT ");
}
puts("------------------------------------");
// Free memory for both strings and structures
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
free(strings[i]);
strings[i] = NULL;
}
free(strings);
strings = NULL;
for(int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
free(structs[i].field);
structs[i].field = NULL;
}
free(structs);
structs = NULL;
} |
Partager