C language Character Construct


#1

In Chapter 14 it compares C’s version of the Objective C example…

I dont understand the point of the line of code:
size_t charCount = strlen(x);
as the variable charCount of type size_t is not used anywhere.

Also strcmp compares a string alphabetically, it does not compare the actual string length?

Did I miss something or is the code imcomplete?

Also why is x free’d but lament is not?


#2

The text indicates that the purpose of showing the C code is to compare it with the equivalent Objective-C. Because length is illustrated for Objective-C, strlen is shown for C. The code isn’t intended to be a complete program.

It’s possible but unlikely that strcmp checks the length of the string at some point. It only needs to scan far enough into each string to determine whether there’s a difference, and in which direction the difference lies, and the length simply doesn’t give you enough information to do much of value here.

Simple strcmp implementation:

int strcmp(char *a, char *b) {
  int i;
  for(i = 0; a[i] != '\0' && b[i] != '\0'; i++) {
    if (a[i] < b[i]) {
      return -1;
    } else if (a[i] > b[i]) {
      return 1;
    }
  }
  /* If we reach this far, one of the strings terminated */
  if (a[i] == '\0' && b[i] != '\0') {
    return -1;
  } else if (a[i] != '\0') {
    return 1;
  } else {
    return 0;
  }
}

You’re right, this is just illustrative.

In C (or Objective-C) a string literal is not allocated on the heap, and thus doesn’t need to be freed, if I recall correctly.

If you don’t use malloc, you don’t use free.

In the code below, free would be necessary:

char *lament = (char *)malloc(9 * sizeof(char));
strncpy(lament, "Why me!?", 8);
free(lament);

#3

Ok cheers. Thanks for taking the time to address all my questions, very helpful!