0
const char* returnStr()
{
    char time[40] = {"France"};
    char* time1;

    time1 = time;

    return time1;
}

int main(int argc, char* argv[])    {
    printf ("return String is %s\n",returnStr());
}

This code returns some junk characters. Won't the const char* not enough to return the local char pointer? Do I have to use the static too in the function?

0

3 Answers 3

5

Do I have to use the static too in the function?

Yes. The const is just a qualifier on the return value, signaling to callers of returnStr that they shouldn't modify the result of the function. It doesn't change time's temporary character.

Sign up to request clarification or add additional context in comments.

Comments

4

When the returnStr function terminates, its stack frame is deallocated - so whatever any local pointers point to is now random data. If you want to return a pointer, you have to allocate it on the heap, with malloc for example.

Comments

3

The time object will exists only until returnStr is running. Once it returns to the function that called it, it is gone, and any pointer to it is invalid. In short, in C you cannot return an array from a function, you can only return a pointer to one. This is why standard library C functions do not allocate strings at all, you must pass in a string and specify how large it is and it will fill it or error out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.