Friday, July 29, 2016

C Basics - Strings in C

Strings are array of characters terminated by a null character '\0'.
A string can be initialized as,

char test[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

char test[] = "Hello";

The C compiler automatically places the '\0' at the end of the string when it initializes the array.

#include <stdio.h>

int main () {

   char test[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
   char test1[] = "Hello";
   printf("test:%s\n", test );
   printf("test1:%s\n", test1 );
   return 0;
}

Strings are actually one-dimensional array of characters. It can also be defined in two-dimension like the following.

char test[3][6] = {"Hello","World","Demo"};

Example:

#include <stdio.h>

int main () { 
   char test[3][6] = {"Hello","World","Demo"};
   printf("test[0]:%s\n", test[0] );   
   printf("test[1]:%s\n", test[1] );   
   printf("test[2]:%s\n", test[2] );   
   return 0;
}
Output of above program,

test[0]:Hello
test[1]:World
test[2]:Demo



Related topics:
Arrays in C   |   Two Dimensional Array in C   |   Passing Array as Function Argument in C   |   Pointers in C   |   Returning Array from a Function in C

List of topics: C Programming

No comments:

Post a Comment