How can I return a string to the operating system in my C code?
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;
}
You could do this in a way similar to scanf
. In other words:
void foo(char **value_to_return) {
*value_to_return = malloc(256); // Store 256 characters
strcpy(*value_to_return, "deposited string");
}
int main() {
char *deposit;
foo(&deposit);
printf("%s", deposit);
return 0;
}