0

I know, there are multiple questions about this on StackOverflow but I couldn't find a fitting solution for my problem.

I want to generate product codes (e.g. 12a, important: numbers and letters) and return them and printf. But when I do it in my main I get no result. When I printf("%s\n", pcode) in my generator function it works, but after return pcode I won't get the result.

char* generate(int num) {
    char pcode[3];
    ... // generating code
    printf("%s\n", pcode); // correct output
    return pcode;
}

int main(void) {
    printf("%s\n", generate(12)); // wrong output
}
nawab
  • 53
  • 4
  • Questions seeking debugging help should generally provide a [mre] of the problem. Your posted code does not compile, because it is incomplete. – Andreas Wenzel Oct 30 '22 at 15:14
  • 1
    `pcode` goes out of scope upon return. See: [Function returning address of local variable error in C](https://stackoverflow.com/q/22288871/5382650) and [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/q/6441218/5382650) – Craig Estey Oct 30 '22 at 15:19
  • You will need to return pointer from `malloc`. Don't forget the null character and to `free` it after using – jvx8ss Oct 30 '22 at 15:23
  • 2
    There are a few remedies: (1) Just add `static` to the definition of `pcode`. (2) Use `malloc` (as mentioned here and in the links). (3) Have the caller pass down a pointer: `void generate(char *pcode,int num) { ... }` and caller: `int pcode[3]; generate(pcode,12);` For (3), now `pcode` is in the _caller's_ scope [on the stack] and _not_ the _callee's_ [where it "disappears" when `generate` returns] – Craig Estey Oct 30 '22 at 15:26
  • 1
    Note that `char pcode[3]` can only store two characters and a null byte. It can't hold `12a` as a string; it isn't long enough. So, once you've fixed the scope problems, you will need to fix the length problems too. – Jonathan Leffler Oct 30 '22 at 15:35
  • Lovely! Thank you all very much! – nawab Oct 30 '22 at 15:37

0 Answers0