HI ,
I am implementing a function for my assignment based on the following information. As you see the main.c file has a function printWithoutDuplicates which prints the strings that are not printed previously. I can use static arrays for this.(Dont confuse with arrays on stack.)
Code:
#ifndef TKK_AS_C_PRINTERS_H
#define TKK_AS_C_PRINTERS_H
/* Prints strings without duplicates * This implies that the function must store all previously printed strings
* and not print a string it has already printed.
* In case of duplicate, nothing is printed.
* As with printWithIndex, a NULL parameter resets the storage and should
* free any memory allocated for the storage. */
void printWithoutDuplicates(const char*);
#endif
Code:
#include "printers.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
static char *arraylist;
static int count = 0;
void printWithoutDuplicates(const char* stringname) {
bool flag = true;
if (stringname) {
if (count > 0) {
for (int i = 0; i < count; i++) {
char *compare = arraylist[i];
if (!strcmp(stringname, compare)) {
flag = false;
}
}
} else {
arraylist = malloc(sizeof (char));
count = 1;
arraylist[0] = stringname;
flag = true;
}
if (flag){
printf("%s\n", stringname);
arraylist = realloc(arraylist, (sizeof (char) *(count + 1)));
arraylist[count] = stringname;
count = count + 1;
}
} else
free(arraylist);
}
Code:
#include "printers.h"
#include <stdio.h>
int main(void)
{
const char* strings[] = {"a string", "another string", "a string", "a better string", "a string", NULL};
printf("Printing without duplicates\n");
for (size_t i = 0;strings[i];i++)
printWithoutDuplicates(strings[i]);
printf("Resetting the duplicate storage\n");
printWithoutDuplicates(NULL);
}
Printing the array gives error when I use the arraylist. Please tell me what to do and how to modify the code. I am stuck there.