• Home
  • What is character array and string array in C?

What is character array and string array in C?

In C language, a character array is an array of characters, and a string is a sequence of characters that is terminated by a null character ‘\0’. A string array is an array of strings, where each string is a sequence of characters that is terminated by a null character.

A character array is defined using the char data type, and it can be initialized using a string literal or an array of characters. For example:

// declare a character array with a string literal
char array1[] = "Hello";

// declare a character array with an array of characters
char array2[] = {'H', 'e', 'l', 'l', 'o', '\0'};

In both cases, the character array will contain the characters “Hello” and a null character ‘\0’ at the end. The size of the character array is 6, including the null character.

A string array is an array of character arrays, where each character array represents a string. It can be declared and initialized using string literals or character arrays. For example:

// declare a string array with string literals
char *array1[] = {"Hello", "World", "!"};

// declare a string array with character arrays
char *array2[] = {
{'H', 'e', 'l', 'l', 'o', '\0'},
{'W', 'o', 'r', 'l', 'd', '\0'},
{'!', '\0'}
};

In both cases, the string array will contain the strings “Hello”, “World”, and “!” as elements. The size of the string array is 3, and the size of each string is determined by the length of the character array that represents it.

Character arrays and string arrays are useful for storing and manipulating strings in C language. They can be used to store and process text data, such as names, addresses, and messages.