C Programming language

String in C
Previous Home Next

String Definition

does not have a string type as other modern programming languages. C only has character type so a C string is defined as an array of characters or a pointer to characters.

Null-terminated String

String is terminated by a special character which is called as null terminator or null parameter (/0). So when you define a string you should be sure to have sufficient space for the null terminator. In ASCII table, the null terminator has value 0.

Declaring String

As in string definition, we have two ways to declare a string.

The first way is, we declare an array of characters as follows:

1. char s[] = "string"; 

And in the second way, we declare a string as a pointer point to characters:

1. char* s = "string";

Declaring a string in two ways

looks similar but they are actually different. In the first way, you declare a string as an array of character, the size of string is 7 bytes including a null terminator. But in the second way, the compiler will allocate memory space for the string and the base address of the string is assigned to the pointer variables.

Looping Through a String

loop through a string by using a subscript.

char s[] = "C string";
int i;
for(i = 0; i < sizeof(s);i++)

You can also use a pointer to loop through a string. You use a char pointer and point it to the first location of the string, then you iterate it until the null terminator reached.

loop through a string using a pointer.

char* ps = s;
while(*ps != '\0'){

Passing a String to Function

A formal way to pass a string to a function is passing it as a normal array.

Previous Home Next