×
☰ Menu

Strings in C

Strings in C are defined as an array of characters. The main difference between a character array and a string is the string is terminated with a special character ‘\0’.

A one-dimensional array of characters with a null ('0') at the end is referred to as a string constant.

char str[]={‘s’, ‘h’, ‘e’, ‘e’, ‘s’, ‘a’, ‘n’,  ‘a’,  ‘v’, ‘I’, ‘\0’};

Each character in the array occupies one byte of memory and the last character is always ‘\0’.

0

1

2

3

4

5

6

7

8

9

10

11

s

h

r

e

e

s

a

n

a

v

i

\0

5555

5556

5557

5558

5559

5560

5561

5562

5562

5563

5564

5565

 

The terminating null (‘\0’) is very important because it is the only method the functions that work with a string can know where the string ends. If string not terminated by a ‘\0’ is not really a string, but just a collection of characters.

char str[]= “shreesanavi”

Note: In this statement declaration ‘\0’ is not mandatory.  C inserts the null character automatically.


Program to printing a String

#include<stdio.h>
int main( )
{
char name[ ] = "shreesanavi" ;
int i = 0 ;
while ( i <= 10 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
return 0;
}

 

Output: 

shreesanavi
--------------------------------
Process exited after 1.065 seconds with return value 0
Press any key to continue . . .