I am trying to make program where I have a linked list that has different names of cities + some other irrelevant stuff. City names are, for ex. "Seattle, Boston, New York, Seattle, Washington, Boston". What I am trying to do is make an array that only has unique names of the cities. So for given example, it would be this: "Seattle, Boston, New York, Washington".
My idea was to make a raw array of strings, which would be just the raw data with all the duplicates and then go through each city and make all the other appearances of them "NULL". For some reason, it does not work properly, I have no idea why.
Also, I would appreciate if you guys could help me with your own, easier versions of the solution.
Here is my code:
void city_list(City *head)
{
City *temp = head;
char** names_raw;
char** names_new;
int num_names = 100;
int curr_pos = 0;
names_raw = malloc(num_names * sizeof(char*));
for(int i = 0; i < num_names; i++)
{
names_raw[i] = malloc(256 * sizeof(char));
}
while(temp != NULL)
{
strcpy(names_raw[curr_pos++], temp->name);
temp = temp->next;
}
names_new = malloc(num_names * sizeof(char*));
for(int i = 0; i < num_names; i++)
{
names_new[i] = malloc(256 * sizeof(char));
}
for(int i = 0; i < curr_pos; i++)
{
if(strcmp(names_raw[i], "NULL"))
{
for(int j = i+1; j < curr_pos; j++)
{
if(!strcmp(names_raw[j], names_new[i]))
{
strcpy(names_raw[j], "NULL");
}
}
strcpy(names_new[i], names_raw[i]);
}
}
for(int i = 0; i < curr_pos; i++)
{
printf("%s\n", names_new[i]);
}
free(names_raw);
free(names_new);
}
When I debug the code, I don't get any errors, but it prints out all the cities, like nothing was done with the array.
strncpy().strcmp, which comparesraw[j]tonew[i]. There's nothing innew[i]at that point in the code. Once you've fixed that, the next problem is thestrcpythat copiesraw[i]intonew[i]. That should be copyingraw[i]intonew[k].