0

C string


A string is an array of char data types and terminated by a null (0) character (also know as the first character in the ASCII character set). The null character is an invisible character in the end of a string. Therefore, always add a number to the length of the array when declaring the char array. For example, char name[21] where name originally contains 20 characters.

In order to assign value to the char array, use strcpy function in the standard C library (stdio.h). For example, strcpy(name, “Mark”). However, it gave me a warning when I tried to compile the source code using gcc. After I googled about the warning message “incompatible implicit declaration of built-in function ‘strcpy’”, I found out that I need to include string.h in addition to stdio.h. Perhaps it’s the difference between Dev-C++ compiler and gcc compiler.

To output to the screen using printf, use %s for string rather than %d for digit/integer. For instance, printf(“The contents of name are %sn”, name).

Here is source code for the basic string program:

#include <stdio.h>
#include <string.h>

main() {

 char name[21];

 strcpy(name, "Mark");
 printf("The contents of name are %sn", name);

 fflush(stdin);
 getchar();
}


There are no posts related to C string.