Home » Uncategorized » Initialization of string in C

Initialization of string in C

There are 2 ways for the initialization of a string in C. The techniques are explained below along with sample programs:

Technique 1:

$ vim string.c

The above command creates a text file using the Vim editor and extension”.c” Next, we type the following program in the file and exit edit mode by pressing Esc. To save the file, we press “:wq” and the editor exits into the terminal.

#include <stdio.h>

int main(void) {
	char message[] = {'H', 'E', 'L', 'L', 'O', '\0'};
	printf("string is : %s\n", message);
	return 0;
}

In the above program, we input the characters of the string into the “char message” function in curly braces along with the last element as “null” character “\0”. We enter the separate characters in single inverted commas.

Compilation of the program:

$ gcc -o string string.c

The above line of code compiles the program into an executable file. This is done with the help of the GNU Compiler Collection utility.

Execution and Output:

$ ./string
string is : HELLO

As seen above, the output of the program converts the single characters in the message function into a string and prints out the complete string.

Technique 2:

$ vim string2.c

The above command creates a text file using the Vim editor and extension”.c” Next, we type the following program in the file and exit edit mode by pressing Esc. To save the file, we press “:wq” and the editor exits into the terminal.

#include <stdio.h>

int main(void) {
	char message[] = "HELLO";
	printf("string is : %s\n", message);
	return 0;
}

In the above program, we input the characters of the string into the “char message” function in double inverted commas without the need for a “null” character or to separate the characters inside the message function. This is the standard way of initializing a string.

Compilation of the program:

$ gcc -o string2 string2.c

The above line of code compiles the program into an executable file. This is done with the help of the GNU Compiler Collection utility.

Execution and Output:

$ ./string2
string is : HELLO

As seen above, the output of the program prints the entire string as entered into the “message” function.

We hope this tutorial is of help. In case you have any other suggestions or questions, do let us know in the comments!


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment