Add static solution as template for dynamic solution.
This commit is contained in:
1 parent
596128d356
commit
68c0349f04
4 files changed
+209
No files matched your search
@@ -0,0 +1,91 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "namesarchive.h"
|
||||
|
||||
static char names[MAX_NAMES][MAX_NAME_LEN];
|
||||
static unsigned int numberOfNames = 0;
|
||||
|
||||
static int findNameIdx(const char *name);
|
||||
static void removeNameByIdx(unsigned int idx);
|
||||
static int compareNames(const void *arg1, const void *arg2);
|
||||
|
||||
// Fügt einen Namen hinzu. Im Fehlerfall (Archiv ist voll) soll 0, ansonsten 1 zurückgegeben werden.
|
||||
// Ist der angegebene Name länger als die zulässige Namenslänge, wird der Name abgeschnitten hinzugefügt. Rückgabe ist dann 1.
|
||||
int addName(const char *name)
|
||||
{
|
||||
if(numberOfNames < MAX_NAMES)
|
||||
{
|
||||
strncpy(names[numberOfNames], name, MAX_NAME_LEN);
|
||||
names[numberOfNames][MAX_NAME_LEN-1] = '\0';
|
||||
numberOfNames++;
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Wie addName. Fügt Namen aber direkt sortiert hinzu. Voraussetzung ist ein bereits sortiertes Archiv.
|
||||
int addNameSorted(const char *name)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Entfernt den angegebenen Namen. Gibt bei Erfolg 1 zurück, ansonsten 0 (Name konnte nicht gefunden werden).
|
||||
int removeName(const char *name)
|
||||
{
|
||||
int nameIdx = findNameIdx(name);
|
||||
|
||||
if(nameIdx >= 0)
|
||||
{
|
||||
removeNameByIdx(nameIdx);
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
int findNameIdx(const char *name)
|
||||
{
|
||||
for(int i = 0; i < numberOfNames; i++)
|
||||
{
|
||||
if(strcmp(names[i], name) == 0)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void removeNameByIdx(unsigned int idx)
|
||||
{
|
||||
for(unsigned i = idx+1; i < numberOfNames; i++)
|
||||
{
|
||||
strncpy(names[i-1], names[i], MAX_NAME_LEN);
|
||||
names[i-1][MAX_NAME_LEN-1] = '\0';
|
||||
}
|
||||
numberOfNames--;
|
||||
}
|
||||
|
||||
int compareNames(const void *arg1, const void *arg2)
|
||||
{
|
||||
const char (*name1)[MAX_NAME_LEN] = arg1;
|
||||
const char (*name2)[MAX_NAME_LEN] = arg2;
|
||||
|
||||
return strcmp(*name1, *name2);
|
||||
}
|
||||
|
||||
// Sortiert die Namen im Archiv aufsteigend.
|
||||
void sortNames()
|
||||
{
|
||||
qsort(names, numberOfNames, sizeof(names[0]), compareNames);
|
||||
}
|
||||
|
||||
// Gibt die Namen zeilenweise aus.
|
||||
void printNames()
|
||||
{
|
||||
for(int i = 0; i < numberOfNames; i++)
|
||||
{
|
||||
printf("%s\n", names[i]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user