简体   繁体   中英

Returning a local pointer in C

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM