Returns the difference between "pointer to a String constant" and "Return array name ".

Source: Internet
Author: User

Returns the difference between "pointer to a String constant" and "Return array name ".

char*getmemory(void){    char p[]=”hello world”;    return p;}void test(void){    char *str=NULL;    str=getmemory(); printf(str);}

Q: What are the results of running the Test function?

Since array p is the data on the stack, the returned array name is the address of the stack memory, that is, the dynamic data zone, and the function is released at the end. Therefore, the returned address points to an uncertain position, str becomes garbled!

If changed:

char*getmemory(void){    char *p=”hello world”;    return p;}void test(void){    char *str=NULL;    str=getmemory(); printf(str);}

The output is correct because the pointer to the String constant is returned, which is the address of the static data zone (constant zone) and can be printed correctly!

Next question:

Q: The following program is used to output "Welcome to Huawei Test". Please note the two errors.

char * GetWelcome(void){    char * pcWelcome;    char * pcNewWelcome;    pcWelcome="Welcome to Huawei Test";    pcNewWelcome=(char *)malloc(strlen(pcWelcome));    //1    if(NULL==pcNewWelcome){        return NULL;        //2    }    strcpy(pcNewWelcome, pcWelcome);    //3    return pcNewWelcome;            //4}

Some people may think the answer is 1 and 4. They think that the address of the returned stack memory will be released except for the function. This is obviously wrong!

The correct answer is 1 and 3.

No memory is allocated to "\ 0" at 1st, and cannot be copied because "\ 0" cannot be copied at 3rd!

Since this function returns the address of the constant area, correct printing is acceptable!

Related Article

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.