A string in C is an array of char values terminated by the null character \0. C has no separate built-in string type, so string operations work with character arrays and pointers.
char name[] = {'p', 'l', 'u', 's', '2', 'n', 'e', 't', '\0'};
char site[10] = "plus2net";
Array indexes begin at 0. The literal "plus2net" contains 8 visible characters plus the terminating null character, so an array of at least 9 characters is required.
char name[10] = "plus2net";
name[3] = '\0';
printf("%s\n", name);
Output
plu
Placing \0 at index 3 makes string functions treat that position as the end.
#include <stdio.h>
int main(void) {
char name[] = "plus2net";
int i = 0;
while (name[i] != '\0') {
printf("%c ", name[i]);
i++;
}
printf("\nCharacters: %d\n", i);
return 0;
}
Output
p l u s 2 n e t
Characters: 8
fgets() is useful when input may contain spaces because it limits the number of characters written to the array.
#include <stdio.h>
#include <string.h>
int main(void) {
char name[40];
printf("Enter your name: ");
if (fgets(name, sizeof name, stdin) == NULL) {
return 1;
}
name[strcspn(name, "\n")] = '\0';
printf("Welcome %s\n", name);
return 0;
}
This restores the distinct vertical-printing example from the original pillar page.
#include <stdio.h>
int main(void) {
char text[] = "Welcome";
int i = 0;
for (i = 0; text[i] != '\0'; i++) {
printf("%c\n", text[i]);
}
printf("Total number of chars = %d\n", i);
return 0;
}
Output
W
e
l
c
o
m
e
Total number of chars = 7
Some older compilers provide the following functions. They are not part of older ISO C standards, so each tutorial also shows a portable modern replacement or explains the implementation requirement.
Arrays of strings in C are primarily part of the Array cluster, but they build directly on the character-array concepts covered here.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.