Hello, I'm trying to write a program which makes a dynamic array of all different words, so if a word is already entered before, it doesn't add the word.
This is my code:
Code:
/* AUTH: Kevin Strijbos
DATE: 07/02/2012
DESC: excercise 14.5.1 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 10
int check_appearance (char* *words, char *toCheck, int index);
int main (void)
{
char* *pntr;
char buffer[21];
int counter, index;
pntr = NULL; // initialize pntr
index = 0; // keeps track of the amount of words in pntr
for (counter = 0; counter < MAX_WORDS ;counter++)
{
printf("Enter a word: ");
fgets(buffer, sizeof(buffer), stdin);
/* delete newline */
if (buffer[strlen(buffer)-1] == '\n')
buffer[strlen(buffer)-1] = '\0';
if (check_appearance(pntr, buffer, index) == 0)
{
pntr = (char* *)(realloc(pntr, sizeof(char *) * (index+1)));
*(pntr+index) = (char *)(malloc(sizeof(buffer)+1)); // +1 for the \0
strcpy((*(pntr)+index), &buffer[0]);
index++;
}
}
/* print list */
for (counter = 0; counter < index ;counter++)
{
printf("WORD %d: %s\n", *(*(pntr+counter)));
free(*(pntr)+counter);
}
free(pntr);
return 0;
}
/* checks if a word is already entered */
int check_appearance (char* *words, char *toCheck, int index)
{
int counter, found;
found = 0;
for (counter = 0; found == 0 && counter <= index ;counter++) // index: how many words there are in the list - 1 (counter is passed)
{
if (strcmp(*(words + counter), toCheck) == 0)
found = 1;
}
return found;
}
Now, the program doesn't work. I think the problem has something to do with the strcmp and strcpy.
It compiles and runs, but when I enter a word I get an error.
Anyone got an idea?