09/10

An Introduction to C

Part IX, 20120910

In the last post, I briefly introduced arrays and strings. Let's look a little more closely.

#include <stdio.h>
#include <string.h>
int main(void) {
  char name1[5] = "Ford";
  char name2[4] = "Jim";
  char name3[8] = "";
  if (strcmp(name1, name2) == 0) {
    printf("Name 1 is the same as Name 2\n");
  }
  else if (strcmp(name1, name2) > 0) {
    printf("Name 1 is larger than Name 2\n");
  }
  else if (strcmp(name1, name2) < 0) {
    printf("Name 1 is smaller than Name 2\n");
  }
  else {
    printf("Something very wrong happened\n");
  }
  strcpy(name3, name1);
  strcat(name3, name2);
  printf("Name 1 and 2 combined is %s\n", name3);
  strcpy(name1, name2);
  printf("Name 1 is now Name 2\n");
  int res = strcmp(name1, name2);
  printf("%d, see?\n", res);
}// end main

So, we have several different things to look at here. First, we have 3 character arrays (strings). We have name1, name2, and name3. name1 is 4 characters long and is terminated by the null character bringing it to 5 elements in length. name2 is 3 characters long and is terminated by the null character bringing it to 4 elements in length. name3 is 7 characters long and is terminated by the null character which brings it to 8 total elements in length.

The next thing to look at is the usage of the strcmp function. We cannot use the normal comparison operators, so we have strcmp to fill the void. If strcmp returns a zero then the two strings being compared are equivalent in content. If strcmp returns a 1 then the first string is larger than the second string. If strcmp returns a negative 1 then the first string is smaller than the second string.

The last thing I want to look at with strings is strcat. The strcat function simply appends the second string listed to the first string listed.