- 1 year ago
How to printf char pointer return from function?
To printf
a char
pointer returned from a function in C, you can use the %s
format specifier with printf
to print a null-terminated string. Here's an example:
c#include <stdio.h>
const char* getString() {
return "Hello, World!";
}
int main() {
const char* str = getString();
printf("%s\n", str);
return 0;
}
In the example above, the getString()
function returns a const char*
pointer to the string "Hello, World!"
. In the main()
function, we assign the returned pointer to the str
variable. Then, we use printf
with the %s
format specifier to print the null-terminated string pointed to by str
.
Make sure the returned char
pointer is pointing to a valid null-terminated string. If the pointer is NULL
or not properly terminated, the behavior will be undefined.
Note: It is essential to ensure that the returned char
pointer is still valid and not freed or deallocated when you attempt to print it using printf
.