1

Trying to write a function which will return a string.

char *type(int type) {
    switch (type) {
        case 1: return "type 1";
        case 2: return "type 2";
        default: return "type 3";
    }
}

Is this the right way to return string? There is no space been allocated for the string by malloc or calloc. So, what's the lifecycle of them? Will the caller allocate new space to store the returned string?

Shuai Xu
  • 89
  • 1
  • 5
  • 2
    "Return a string"? You are not returning a string here. You are returning a **pointer** to a string. `char *` is a pointer type. – AnT stands with Russia May 30 '19 at 00:13
  • @AnT pointer to a string or pointer to the first character in the string? – Ajay Brahmakshatriya May 30 '19 at 00:25
  • 2
    @Ajay Brahmakshatriya: Technically, it is a pointer to the first character in the string, as you said. However, the language standard itself explicitly defines what "a pointer to a string" means in **7.1.1 Definitions of terms**: "*A pointer to a string* is a pointer to its initial (lowest addressed) character". So, in standard parlance we just use the more concise shorter form: *a pointer to a string*. – AnT stands with Russia May 30 '19 at 00:31
  • @AnT Ah! I see. Learnt something new! Thanks. It just seems funny that the language defines 1. what a string is, 2. what a pointer to X is and separately defines 3.pointer to a string (something not consistent with combining 1 and 2). – Ajay Brahmakshatriya May 30 '19 at 00:33
  • Constant string literals like "type 1" are allocated at compile time, often in read-only memory, and therefore have a lifetime of the entire program. It's fine to return such a pointer--what it points to isn't going anywhere. – Lee Daniel Crocker May 30 '19 at 01:04
  • Note the use of `const` in the linked question. Also note that the caller must not free the string. – ikegami May 30 '19 at 01:11

0 Answers0