How to return a string in my C code?

I start C, and this is my C code:

#include <stdio.h> #include <stdlib.h> main() { printf("Hello world !\n"); return 'sss'; } 

which will show an error

so how to return a string to C code?

+8
c string return
source share
6 answers

If you want to return a string from a function (except the main one), 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; } 
+12
source share

The magic is in the static , which retains the contents of the string memory even after the function completes. (You can consider it as an extension of the scope of a variable.)

This code takes each character every time, then concatenates them into a string and saves it to 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; } 
+4
source share

You can do this in a simple way before scanf . in other words:

 void foo(char **value_to_return) { *value_to_return = malloc(256); // store 256 chars strcpy(*value_to_return, "deposited string"); } int main() { char *deposit; foo(&deposit); printf("%s", deposit); return 0; } 
+2
source share

Unfortunately, there is no way to do this.

You can add something to the end of your c program, for example:

 int main() { int err = 0; // 0 is "success" is most c programs printf("hello world!\n"); switch( err ) { case 0: printf("program shutdown succesfully!\n"); break; case 1: printf("we had an issue somewhere. please fix your input data\n"); break; //case 2, 3, etc... }; return err; } 
0
source share

You are not returning a string. Exit applications with an integer exit code.

Normally, a return return of 0 will always indicate that your application exited without errors / completed. You return an integer other than 0 to indicate that your application came out anonymously.

You can create an exception and handle it using the logging method above in the call stack, or you can simply return something other than 0, and make sure you include in your release notes what each integer number of errors means.

0
source share

Perhaps you can use environment variables for this. Not sure though.

-2
source share

All Articles