I am a C beginner and this is my C code:
#include <stdio.h>
#include <stdlib.h>
main()
{
printf("Hello, World!\n");
return 'sss';
}
That will show an error. So how can I return a string in C code?
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid.
There are two methods to return a String in Java: the “System. out. println()” method or the “return” statement.
If you are looking to return a string from a function (other than main
), you should do something like this.
#include <stdio.h>
const char * getString();
int main()
{
printf("Hello, World!\n");
printf("%s\n", getString());
return 0;
}
const char * getString()
{
const char *x = "abcstring";
return x;
}
The magic is in the key word static
which preserves the memory content of the string even after the function ends. (You can consider it like extending the scope of the variable.)
This code takes one character each time, then concatenates them in a string and saves it into a file:
#include <stdio.h>
#include <conio.h>
char* strbsmallah ()
{
static char input[50];
char position = 0, letter;
scanf("%c", &letter);
while (letter != '~') { // Press '~' to end your text
input[position] = letter;
++position;
scanf("%c", &letter);
}
input[position] = '\0';
char *y;
y = (char*) &input;
//printf("%s\n ", y);
return y;
}
int main() {
printf("\n");
FILE *fp;
fp = fopen("bsmallah.txt", "w+");
fprintf(fp, strbsmallah());
while (!_kbhit())
;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With