Expanding the accepted answer by adding more utility functions
bool store_in(char *string, char *array[], size_t size);
bool delete_in(char *string, char *array[], size_t size);
and test program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h> // bool C99
bool exists_in(char *string, char *array[], size_t size)
{
size_t i;
for(i = 0; i < size; ++i)
{
if (array[i] && strcmp(string, array[i]) == 0)
{
printf("Exists: %s\n", array[i]);
return true; // exists
}
}
return false;
}
bool store_in(char *string, char *array[], size_t size)
{
size_t i;
for(i = 0; i < size; ++i)
{
if (array[i] == 0)
{
array[i] = string;
printf("Storing: %s\n", array[i]);
return true; // stored
}
}
return false;
}
bool delete_in(char *string, char *array[], size_t size)
{
size_t i;
for(i = 0; i < size; ++i)
{
if (array[i] && strcmp(string, array[i]) == 0)
{
printf("Delete: %s\n", array[i]);
array[i] = NULL;
return true; // deleted
}
}
return false;
}
int main()
{
char *my_array[100] = { NULL }; // initialize array with NULL
// (all elements will be initialized to 0 with this construction)
//1.
if (! exists_in("123", my_array, 100) ) // Does not exists
store_in("123",my_array, 100); // It will store
printf("\n");
//2.
if (! exists_in("123", my_array, 100)) // Exists
store_in("123",my_array, 100); // It will not store
printf("\n");
//3.
if (exists_in("123", my_array, 100))
delete_in("123",my_array, 100); // It will delete
printf("\n");
//4.
if (! exists_in("123", my_array, 100)) // Does not exists
store_in("123",my_array, 100); // It will store
return (0);
}
Output:
Storing: 123
Exists: 123
Exists: 123
Delete: 123
Storing: 123
ifstatement's braces are missing.