Search code examples
cmallocstrcmp

Using malloc with functions and strcmp


I'm trying to use malloc with a function I wrote in order to grow a list of unique states(no duplicates)

My file contains strings such as;

Kmart, 295 Hartford Turnpike, Vernon CT

The function I wrote extracts the states("CT") from a file;

#define MAX_CHARS_PER_LINE 80
void getState(char strState[], const char strLine[])
{
   char newLine[MAX_CHARS_PER_LINE+1];
   char newState[MAX_CHARS_PER_LINE+1];

   strcpy(newLine, strLine); 
   char* token = strtok(newLine, ",");

   if(token != NULL)
   {
     token = strtok(NULL,",");
     token = strtok(NULL, ",");
   }
   strcpy(newState, token);

   unsigned long length = strlen(newState)-5; 

   strcpy(strState, newState+length); 

}

This is my main function which I am trying to find the unique list of states using strcmp and grow it using malloc;

int main(void)
{
   char **states[3];
   char buffer[MAX_CHARS_PER_LINE+1];

   FILE* fptr;    
   fptr = fopen(fileName, "r");

   if(fptr == NULL)
   {
     exit(EXIT_FAILURE);
   }
   else
   {
     while(fgets(buffer, sizeof(buffer), fptr))
     {
       getState(states, buffer);                  
     }

     for(int i = 0; i < 3; i++)
     {
        for(int j = 0; j < 3; j++)
        {
            if(strcmp(states[i], states[j]))
            {
                states[i] = malloc(3* sizeof(states));
            }            
        }        
    }
    fclose(fptr);       
    free(states);
}

return EXIT_SUCCESS;
}

I'm a bit confused on how to correctly use malloc and strcmp to get this unique list. My get state function works fine, it's just my main I have problems with


Solution

  • A few things:

    a. In the getState function, change the length variable from strlen(newState)-5 to strlen(newState)-2. States are only 2 letters, and strlen doesn't count the terminating character.

    b. Don't use a triple pointer for "states"; use a double pointer. It should just be a string of strings.

    c. Use the iterator for the states list for getState. MAKE SURE TO RE-MALLOC TO INCREASE THE SIZE AND COPY THE OLD STATES WITH A BACKUP POINTER BEFORE CALLING GETSTATES

    d. Iterate through the states array with getState.

    e. Make either a second array for the second iteration to copy each unique state name, OR just make a new string variable, use getState on that, then iterate through states with strcmp, and if there's no matches, THEN add that state to the states array.