Skip to main content

Declaration of Strings in C

String Declaration

  • String declaration in C refers to the process of creating a variable that can hold a string of characters.

  • In C, a string is declared as an array of characters.

  • The size of the array determines the maximum length of the string that can be stored in the variable.

The syntax for declaring a string in C is as follows:

char string_name[array_size];

Explanation

  • Here, string_name is the name of the string variable, and array_size is the size of the character array that will hold the string.
  • It specifies the maximum number of characters that the string can hold, including the null terminator.

For example:

The following code declares a string named greeting that can hold up to 19 characters:

char greeting[20];

Note that when declaring a string in this way, it does not have an initial value. To give a string an initial value, you can use the following syntax:

char greeting[20] = "Hello, World!";

String Declaration - Example

Here's an example of a C program that declares a string and uses it:

#include <stdio.h>

int main()
{
// Declare a string to store a greeting message
char greeting[20] = "Hello, World!";

// Print the greeting message to the console
printf("%s\n", greeting);

// Return 0 to indicate that the program has executed successfully
return 0;
}
Output:

Explanation

  • We declare a string named greeting with an initial value of "Hello, World!".
  • We then use the printf function to print the contents of the string to the console.
  • The format specifier %s is used to print a string, and the \n character is used to print a newline after the message.
  • Finally, the program returns 0 to indicate that it has executed successfully.