Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a string to the operating system in my C code?

Tags:

c

string

return

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?

like image 837
zjm1126 Avatar asked Feb 08 '11 03:02

zjm1126


People also ask

Can you return Strings in C?

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.

How do you return a string in Java?

There are two methods to return a String in Java: the “System. out. println()” method or the “return” statement.


2 Answers

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;
}
like image 195
aNish Avatar answered Sep 24 '22 12:09

aNish


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;
}
like image 20
Jay Shenawy Avatar answered Sep 21 '22 12:09

Jay Shenawy