Char STR [] = "Hello World"; and char * STR = "Hello World"; Difference

Source: Internet
Author: User
Char * stra ()
{
Char STR [] = "Hello World ";
Return STR;
}

What is the problem with this program? How can I modify it?

Resolution:The address in this STR is the first address of "Hello World" in the stack of the function. After the function call is complete, the stack frame is restored to the status before calling stra, the temporary space is reset, And the stack is "retracted". The stra stack frame is no longer within the scope of access. This program can output the results correctly, but this access method violates the function's stack frame mechanism.

However, if you call another function, you will find that this method is unreasonable and dangerous.

If you want to obtain the correct function, change it to the following:

Char * stra ()
{
Char * STR = "Hello World ";
Return STR;
}

First, we need to clarify char * STR and char STR []:

Char STR [] = "Hello World ";

Is to allocate a local array. A local array is a local variable, which corresponds to a stack in the memory. After the lifecycle of a local variable ends, the variable does not exist.

Char * STR = "Hello World ";

 

Is a string pointing to the constant area, located in the static storage area, it remains unchanged during the life of the program, so the string is still in. Whenever you call stra, it always returns the same read-only memory block.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.