Strings in C

C doesn’t know about strings. It knows about characters, and thus, a string is an array of characters like so:

char the_string[] = "this is my fancy string";

Another way to allocate a number of chars is this:

char the_string[50];

To show that its really an array:

#include <stdio .h>
 
int main() {
  char some_array[] = {'a', 'b', 'c'};
  printf("%s\n", some_array);
  return 0;
}
</stdio>

Which yields:

abc

Here we create an array of characters named the_string. A string in C is terminated by the “\0″ (NULL) character.

Example of passing a string to a method called print:

#include <stdio .h>
 
void print(char string[]) {
  printf("%s\n", string);
}
 
int main() {
  print("test 1 2 3");
  return 0;
}
</stdio>

Leave a Reply