Search code examples
carrayspointersstrcmp

Working with pointers: program that checks if strings are in lexicographical order


I am trying to make a program which checks if a list of Strings are in lexicographical order or not. If it is in order, the program should return 1, if not 0. To test the program I introduced the strings AA, BB and CC which obviously should be in order. However, the program return 0...

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


int lex_sorted(const char* array[]){
  int k;

  for(k=0;*array+k+1!=NULL;k++){

    if(strcmp(*array+k,*array+k+1)<0){
      return 0;
    }

  }


  return 1;

}



int main(void){
  int result;
  const char* array[]={"AA","BB","CC",NULL};
  result= lex_sorted(array);
  printf("%d\n",result);
  return 0;

Solution

    1. *arr+k and *(arr+k), *arr+k+1 and *(arr+k+1) are two different expressions.
    2. It should be strcmp() > 0, not strcmp() < 0 as per requirement.
    3. i should be initialised before each iteration (inner loop)

    Tips:

    • It would be easy for others to read if arrays are indexed. arr[k] instead of *(arr+k)
    • Indetation can make a big difference while reading code.