-3

I'm having trouble with strings and c.

I'm trying to do something very simple: converting an int into a string and printing it into a txt file in the following fashion.

const char * test_string() {
    char s[5];
    int num = 123;
    sprintf(s, "%d", num);
    return s;
}

int save() {
    FILE *fh = fopen("test.txt", "w");
    const char * text = test_string();
    fprintf(fh, "%s", text);
    fclose(fh);
}

Yet, for this simple task, I'm getting the following result:

Üþ(

I'd like some assistance with this problem. Thanks in advance.

miroki123
  • 27
  • 1
  • 2

1 Answers1

4

s is a local variable in test_string, so it is destroyed when test_string returns. Then, you try to print the value of a variable that no longer exists.

user253751
  • 57,427
  • 7
  • 48
  • 90