Skip to content

C Strings

  • Strings aren’t actually strings in C, they’re pointers (of char type)

String variables

char *s = "Hello, World!\n";
printf("%s\n",s);
for (int i = 0; i < 13; i++){
printf("%c\n", s[i]);
}
char a[] = "Goodbye World!";
printf("%s\n",a);
for (int i = 0; i < 15; i++){
printf("%c\t", a[i]);
}

String initializers

char *s = "Hello, world!";
char t[] = "hello world";
  • But these 2 are subtly different.
    • (Immutable) The first one is a pointer to a string literal (i.e a pointer to the first char in a string)
      char *s = "Hello, world!";
      // this will create a pointer s point to read-only value in the op
      s[0] = 'z'; // ERROR
    • (Mutable) The second one is different, it’s a mutable copy of the string that we can change at will:
      char t[] = "hello world";
      // equivalent to
      // char t[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};
      t[0] = 'z'; // No problem
      printf("%s\n", t); // "zello, again!"

String length

When you’re making a new language, you have basically two options for storing a string in memory:

    1. Store the bytes of the string along with a number indicating the length of the string.
    1. Store the bytes of the string, and mark the end of the string with a special byte called the terminator.

If you want strings longer than 255 characters, option 1 requires at least two bytes to store the length. Whereas option 2 only requires one byte to terminate the string. So a bit of savings there, so C took approach #2.

In C, a “string” is defined by 2 basics characteristics:

  • A pointer to the first character in the string
  • A Zero-valued byte ( or NUL character) somewhere in memory after that pointer that indicates the end of the string
char *s = "Hello!"; // Actually "Hello!\0" behind the scenes
  • Getting string length:
#include <stdio.h>
#include <string.h>
int main(void){
char *s = "Hello, World!";
printf("The string is %zu bytes long.\n", strlen(s));
}
  • Behind the scene, the strlen() basically looks like this:
int strlen(char *s) {
int count = 0;
while (s[count] != '\0'){
count++;
}
return count;
}

String copy

  • Use strcpy
int main(void){
char *s = "Hello, World!";
char t[100];
strcpy(t,s);
t[0] = 'z';
printf("%s\n", s);
printf("%s\n", t);
}
  • Use memcpy
#include <stdio.h>
#include <string.h>
int main(){
char s[] = "Goats!";
char t[100];
memcpy(t,s,7); //Copy 7 bytes - inclding the NUL terminator;
printf("%s\n", t);
}

Array of strings

char *a[10];
//This declares an array of 10 char pointer.
//Each pointer points to a "string"