loading...

Pointers and strings

mikkel250 profile image mikkel250 ・1 min read

Overview

As seen in the previous post in this series, pointer arithmetic is a handy way to iterate through arrays, and since strings are an array data structure (an array of characters), they are also useful and give the programmer a lot of flexibility when working with strings.
For example, a character pointer can be used to copy a string, using a while loop, that is much more efficient (in terms of lines of code) than a for loop. In the example below, both methods will copy the same string:

//using a for loop (you can eliminate the first parameter because *to already points to the first element's address)
void copyString(char *to, char *from)
{
 int i;

 for ( ; *from != '\0'; ++from, ++to)
 // could also be written as for (*to; *from != '\0'; ++from, ++to), but the *to is not necessary as noted above
 {
   *to = *from;
 }
 *to = '\0';
}

//using a while loop
void copyStringSmall(char *to, char *from)
{
  while (*from)
  {
    *to++ = *from++;
  }
  to = '\0';
  // add the null terminator to the end of the string that is copied after the loop ends
}

int main(void)
{
  char string1[] = "a string to copy";
  char string2[];
  char string3[];

  copyString(string2, string1);
  copyStringSmall(string3, string1);

  printf("for loop: %s \n", string2);
  printf("while loop: %s \n", string3);
}

The reason the while loop can be so compact is because the null character is equivalent to zero, i.e. it is "falsy", so the while loop will terminate when it hits the end of the string. In C, booleans are represented by integers, 0 is false, and 1 (or, really anything nonzero) is true.

Posted on by:

mikkel250 profile

mikkel250

@mikkel250

I've been tinkering with computers since I was a teen. I'm currently pivoting from my current role as Tech Support manager to Full Stack Web Developer. I'm actively seeking employment in the field.

Discussion

pic
Editor guide