I am writing C function, which updates array of strings, only if given elements are unique. I have implemented this function like this:
char *cities[100];
/* adds 2 names if they're unique instances and updates total number of cities names
if necessary */
int addCity(char* city1, char* city2, char** arr, int amount) {
int toReturn = amount;
int i;
int flag1 = 0;
int flag2 = 0;
// checking whether first city already exists
for (i = 0; i < amount; i++ ) {
if (strcmp(arr[i], city1) == NULL) {
flag1 = 1;
break;
}
}
if (flag1 == 0) {
arr[amount] = city1;
toReturn++;
}
// 2nd city
for (i = 0; i < amount; i++ ) {
if (strcmp(arr[i], city2) == NULL) {
flag2 = 1;
break;
}
}
if (flag2 == 0 && flag1 == 1) {
arr[amount] = city2;
toReturn++;
}
if (flag2 == 0 && flag1 == 0) {
arr[amount+1] = city2;
toReturn++;
}
return toReturn;
}
It looks that I get some warnings(comparison between pointer and integer) when trying to compare element of String array and String itself. How can I get rid of that? And overall, what else can be improved in this function?
In addition, I doubt about arr[amount] = city1, but when i use strcpy() program does not work at all.
charwith specific conventions. However, your code does not use an array of that, but pointers. A pointer is not an array (nor a "string").