How to Use %s in C Correctly: Format Specifiers Explained

How to Use %s in C Correctly: Format Specifiers Explained

In C, the %s format specifier is used to print a string value. To use it correctly, you need to pass the string value as an argument to the printf() function. Here’s an example:

c
#include <stdio.h>

int main() {
char str[] = "Hello, World!";
printf("The string is: %s\n", str);
return 0;
}

When the program is executed, it will output:

csharp
The string is: Hello, World!

It’s important to note that the string value must be a null-terminated string, meaning that it must end with the \0 character. This is what makes it a C string. If the string value is not null-terminated, the behavior of the printf() function is undefined.

Al Mahbub Khan
Written by Al Mahbub Khan Full-Stack Developer & Adobe Certified Magento Developer

Full-stack developer at Scylla Technologies (USA), working remotely from Bangladesh. Adobe Certified Magento Developer.