// string_test.c - Demonstration of strings in C

#include <stdio.h>
#include <stdlib.h>

#define MAX_STR_LEN 256

#define ILLEGAL_ARGUMENTS -1

int readLine(char *str,unsigned max_length);
unsigned stringLength(char *str);
void stringCopy(char *dst,char *src);

//------------------------------------------------------------
int main()
{
  // requesting dynamic allocation of memory for the array
  char *test_string = malloc((MAX_STR_LEN + 1) * sizeof(char));
  int length;

  length = readLine(test_string,MAX_STR_LEN);
  if (length != ILLEGAL_ARGUMENTS)
  {
    char *copied_string = malloc((MAX_STR_LEN + 1) * sizeof(char));

    printf("Input was: %s\n",test_string);
    printf("Length of String is: %u\n",
            stringLength(test_string));

    stringCopy(copied_string,test_string);

    printf("Copied String is: %s\n",copied_string);
    printf("Length of String is: %u\n",
           stringLength(copied_string));
  
    free(copied_string);
  }

  free(test_string);
  return(0);
}

//------------------------------------------------------------
int readLine(char *str,unsigned max_strlen)
{
  char character_read = '\0';
  unsigned num_chars = 0;

  if ((max_strlen <= 0) || (str == NULL))
    return(ILLEGAL_ARGUMENTS);

  while((character_read = getchar()) != '\n')
  {
    *str++ = character_read;
    if (++num_chars >= max_strlen)
      break;
  }
  *str = '\0';
  return(num_chars);
}

//------------------------------------------------------------
unsigned stringLength(char* str)
{
  unsigned length = 0;
  while(*str++)
    length++;
  return(length);
}

//------------------------------------------------------------
void stringCopy(char *dst,char *src)
{
  while(*dst++ = *src++)
    ;
}
