DEV Community


Posted on

Pointers and strings


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);
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)