Use sprintf. (This is NOT safe, but OP asked for an ANSI C answer. See the comments for a safe version.)

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the format parameter, the function expects at least as many additional arguments as needed for format.

Parameters:

str

Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.

format

C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

Example:

// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");
Answer from akappa on Stack Overflow
🌐
freeCodeCamp
freecodecamp.org › news › how-to-print-a-string-in-c
C Print String – How to Print a String in C
April 17, 2024 - Here is an example of how to create ... automatically includes the null terminator, \0, at the end of Hello world!. The printf() function is one of the most commonly used ways of printing strings in C....
🌐
GeeksforGeeks
geeksforgeeks.org › c language › strings-in-c
Strings in C - GeeksforGeeks
November 14, 2025 - printf("The string is: %s\n", str); %s is the format specifier used to print a string. printf starts at the memory location of str and prints each character until it finds the terminating null character '\0'.
Discussions

Printing strings using pointers in c.
First of all, char * ptr points to the first character of the string(or think of it as an array of chars) which you have taken to be "yemef". So ptr essentially points to 'y'. Now, another thing to keep in mind is that all C strings are null terminated meaning that a '\0' is automatically appended to a string. Why is that? Well we know that ptr points to the first character but it has no way of knowing how long the string is(or how many chars follow the first character). So when the time comes to do some work on the string, like printing to the console which you have done, %s goes on from the character pointed to by the pointer till it hits a null-terminator i.e '\0'. That is why the actual string is getting printed. You can try running this: #include int main() { char * my_str = "Hello\0 World"; // Note the placement of '\0' printf("%s", my_str); // Because we placed the null terminator after "Hello" // We only print "Hello" and simply avoid "World" } More on reddit.com
🌐 r/C_Programming
13
3
March 26, 2022
How to take a string as input and print it without specifying size?
All the languages that do this stuff easily actually use “complex code” under the hood. Welcome to C. More on reddit.com
🌐 r/C_Programming
33
23
September 16, 2023
How do I print out the null value in a string?
You can have characters that don't have any associated glyphs — that is, that have no graphical representation. This will almost certainly be the case with the null character (and other so-called "control" characters) on your system. So what do you expect to see? More on reddit.com
🌐 r/C_Programming
23
0
December 4, 2023
[C] How can I print a string only once in a for-loop?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
7
7
February 15, 2024
Top answer
1 of 8
136

Use sprintf. (This is NOT safe, but OP asked for an ANSI C answer. See the comments for a safe version.)

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the format parameter, the function expects at least as many additional arguments as needed for format.

Parameters:

str

Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.

format

C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

Example:

// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");
2 of 8
36

If you have a POSIX-2008 compliant system (any modern Linux), you can use the safe and convenient asprintf() function: It will malloc() enough memory for you, you don't need to worry about the maximum string size. Use it like this:

char* string;
if(0 > asprintf(&string, "Formatting a number: %d\n", 42)) return error;
log_out(string);
free(string);

This is the minimum effort you can get to construct the string in a secure fashion. The sprintf() code you gave in the question is deeply flawed:

  • There is no allocated memory behind the pointer. You are writing the string to a random location in memory!

  • Even if you had written

    char s[42];
    

    you would be in deep trouble, because you can't know what number to put into the brackets.

  • Even if you had used the "safe" variant snprintf(), you would still run the danger that your strings gets truncated. When writing to a log file, that is a relatively minor concern, but it has the potential to cut off precisely the information that would have been useful. Also, it'll cut off the trailing endline character, gluing the next log line to the end of your unsuccessfully written line.

  • If you try to use a combination of malloc() and snprintf() to produce correct behavior in all cases, you end up with roughly twice as much code than I have given for asprintf(), and basically reprogram the functionality of asprintf().


If you are looking at providing a wrapper of log_out() that can take a printf() style parameter list itself, you can use the variant vasprintf() which takes a va_list as an argument. Here is a perfectly safe implementation of such a wrapper:

//Tell gcc that we are defining a printf-style function so that it can do type checking.
//Obviously, this should go into a header.
void log_out_wrapper(const char *format, ...) __attribute__ ((format (printf, 1, 2)));

void log_out_wrapper(const char *format, ...) {
    char* string;
    va_list args;

    va_start(args, format);
    if(0 > vasprintf(&string, format, args)) string = NULL;    //this is for logging, so failed allocation is not fatal
    va_end(args);

    if(string) {
        log_out(string);
        free(string);
    } else {
        log_out("Error while logging a message: Memory allocation failed.\n");
    }
}
🌐
Reddit
reddit.com › r/c_programming › printing strings using pointers in c.
r/C_Programming on Reddit: Printing strings using pointers in c.
March 26, 2022 -

i was studying about printing strings using pointers whithout having to use conditional statement for each character inside a string . and here the pointer was equated to actual string and i got confused as pointer ususally means only address of that string.

#include<stdio.h>

int main() {
    //char str[]="yemef";
    char *ptr="yemef";
    printf("%s",*ptr);
    //printf("%s",str);

    return 0;
}

// generally we use something like char *p=&str[] or char *ptr=str( as str=&str[]

but here we are equating pointer directly to the string and i wanna know why?

how are we using pointer and printing actual string and even in printf statement we are using address to print the string. i am confused . i need help.

Top answer
1 of 3
8
First of all, char * ptr points to the first character of the string(or think of it as an array of chars) which you have taken to be "yemef". So ptr essentially points to 'y'. Now, another thing to keep in mind is that all C strings are null terminated meaning that a '\0' is automatically appended to a string. Why is that? Well we know that ptr points to the first character but it has no way of knowing how long the string is(or how many chars follow the first character). So when the time comes to do some work on the string, like printing to the console which you have done, %s goes on from the character pointed to by the pointer till it hits a null-terminator i.e '\0'. That is why the actual string is getting printed. You can try running this: #include int main() { char * my_str = "Hello\0 World"; // Note the placement of '\0' printf("%s", my_str); // Because we placed the null terminator after "Hello" // We only print "Hello" and simply avoid "World" }
2 of 3
5
There is no native string type in C. The only thing you have are pointers to characters. Arrays in C behave a lot like pointers, especially in that the size of what is pointed to/the data of the array is unknown (well, the size can be fixed at compile time, but that does not matter for this example). Your question makes sense: If we only have pointers to characters, how are strings printed? The answer is that instead of remembering the length, C strings are terminated by a 0 byte, and when printf is asked to print a string, it will simply print all characters from the first character pointed to until the first 0 byte. When you write a string literal in C using "double quotes", the compiler automatically adds a 0 byte at the and of that character sequence. The string is then simply represented by a pointer to the first character of that sequence, here the 'd'.
🌐
W3Schools
w3schools.com › c › c_strings.php
C Strings
This is the easiest way to create a string in C. You should also note that you can create a string with a set of characters. This example will produce the same result as the example in the beginning of this page: char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'}; printf("%s", greetings); Try it Yourself »
🌐
Quora
quora.com › How-do-I-print-a-string-using-the-write-function-in-the-C-language
How to print a string using the write() function in the C language - Quora
Answer (1 of 4): Write() is a system call. Printf(), etc are glibc library functions that run in your application that ultimately call write(). The glibc functions make it much easier to manage text. Write takes a buffer and copies it to a device. You open the device through the devices driver i...
🌐
Scaler
scaler.com › home › topics › how to print string in c
How to Print String in C - Scaler Topics
April 16, 2024 - In the sections below, let's look at the methods used to print a string. puts(<str_name>): puts() function takes a string character array name as an argument to print the string in the console.
Find elsewhere
🌐
Medium
medium.com › @akxay › all-the-ways-to-print-strings-in-c-with-code-examples-8cdb1105f349
🧵 All the Ways to Print Strings in C (With Code Examples)
June 4, 2025 - This method ensures we don’t print beyond the string’s bounds. You can also directly use printf("%s", name); to simplify.
🌐
Linux.org
linux.org › home › forums › general linux forums › general computing
How Do I Print A String In C.....? | Linux.org
May 6, 2016 - :3 Also, I suspect that @ryanvade is better in Python than in C....... S · Joined · Jun 17, 2020 · Messages · 27 · Reaction score · 3 · Credits · 200 · Jun 25, 2020 · #8 · int main() { char z[100]; printf("Enter a string\n"); gets(z); printf("The string: %s\n", z); return 0; } Staff ...
🌐
Sololearn
sololearn.com › en › Discuss › 2521973 › printing-of-string-with-s-format-specifier-yields-no-output
Printing of string with %s format specifier yields no output | Sololearn: Learn to code for FREE!
The question is asking for the output of the following code: char p[20]; char *s = "string"; int length = strlen(s); for (int i = 0; i < length; i++) p[i] = s[length - i]; printf("%s", p); The correct answer is No output.
🌐
Programiz
programiz.com › c-programming › c-strings
Strings in C (With Examples)
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of the name string. To print the string, we have used puts(name);.
🌐
Wikipedia
en.wikipedia.org › wiki › Printf
printf - Wikipedia
January 16, 2026 - In 1991, a printf command was included ... does not use the postional arguments with a "$" symbol (n$) in the same way as printf() function: str="AA BB CC" # simple string with 3 fields set -- $str # convert fields to positional parameters printf ...
🌐
Scaler
scaler.com › home › topics › strings input and output functions in c
Strings Input and Output functions in C
November 16, 2023 - Here, s is the pointer which points to the array of characters which contains the string which we need to output. Let us look at an example to understand the printf() function in C.
🌐
CodeScracker
codescracker.com › c › program › c-program-print-string.htm
C program to read and print strings
#include<stdio.h> #include<conio.h> int main() { char str[100]; printf("Enter any sentence: "); scanf("%s", str); printf("\nYou have entered:\n"); printf("%s", str); getch(); return 0; } ... Now enter any string, say "we love codescracker," and press ENTER. Here is the sample output: As you ...
🌐
Scribd
scribd.com › document › 775094859 › C-Print-String-How-to-Print-a-String-in-C
C Print String - How To Print A String in C | PDF
C Print String – How to Print a String in C - Free download as PDF File (.pdf), Text File (.txt) or read online for free.
🌐
Florida State University
cs.fsu.edu › ~myers › c++ › notes › c_io.html
Basics of Formatted Input/Output in C
scanf("%d%f %c", &i, &f, &c); There's a space betwen the %f and the %c in the format string. This allows the user to type a space. Suppose this is the typed input: 12 34.5678 N Then the character variable c will now contain the 'N'. input2.c -- a version of the example with this change is linked ...