Search code examples
carraysstringstrcmpstrlen

Function for checking a string freezes


The program is supposed to use the hydroxide function to check an inputted string to see if it ends in "oh" (or "ho") and return a 1 value if it does. Here is what I have written and when I run the program it just freezes. I am still a beginner so I apologize in advance if this is a stupid question.

#include <stdio.h>
#include <string.h>

#define MAX_LEN 10

int hydroxide(char *compound);

int main(void)
{
  char compound[MAX_LEN];
  int i, num;

  printf("Enter compound> \n");
  scanf("%s", compound);

  for (i = 0; i < strlen(compound); ++i) {
    if (islower(compound[i]))
        compound[i] = toupper(compound[i]);
  }

  num = hydroxide(compound);

  printf("%d", num);

  return(0);
}

int hydroxide(char *compound)
{
  char *end[4], *temp;
  int last, status;

  last = strlen(compound);

  strcpy(end[], &compound[last - 2]);

  if (strcmp(end[last - 2],end[last - 1]) > 0) {
    temp = end[last - 2];
    end[last - 2] = end[last - 1];
    end[last - 1] = temp;
  }

  if (*end[last - 2] == 'H') {
    if (*end[last - 1] == 'O')
      status = 1;
  }

  return(status);
}

Solution

  • char end[4], *temp;  /* Change to end[4] */
    ...
    ...
    strcpy(end, &compound[last - 2]);  /* Change to end */
    ...
    ...
    /*  Commented
     * if (end[0],end[1]) > 0) {
     *  temp = end[last - 2];
     *  end[last - 2] = end[last - 1];
     *  end[last - 1] = temp;
     * }
     */
    /* Condition updated */
    if ( (end[0] == 'H' && end[1] == 'O') || (end[0] == 'O' && end[1] == 'H') ) {
      status = 1;
    }
    

    Live Example here