C++ 局部变量

先看一个小程序

#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
char *test(){
       char buffer[20]="1234";
       return buffer;
}

int main(){
    cout<<test()<<endl;//什么都没有
}

局部变量(自动变量)在堆栈中分配内存。当包含局部变量的函数或者代码块退出时,它们所占的内存便会被回收。它们的内容肯定会被下一个调用函数覆盖。这一切取决于堆栈中先前的自动变量位于何处,活动函数声明了什么变量,写了什么内容等。原先自动变量地址的内容可能立即被覆盖,也可能稍后被覆盖。
解决这个问题可参照如下

#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
void test4(char *s){
        strcpy(s,"12345");
}
char *test3(){
       static char buffer[20]="1234";
       return buffer;
}
char *test2(){
        char * buffer=(char *)malloc(10*sizeof(char));
        strcpy(buffer,"12345");
        return buffer;
}
char *test1(){
    return "dsdsds";
}

int main(){
    cout<<test1()<<endl;//返回指向字符串常量的指针

    cout<<test2()<<endl;//显示分配内存,保存返回的值

    cout<<test3()<<endl;//使用静态数组。只有拥有指向该数组的指针的函数才能修改这个静态数组。缺点是,第一次调用的时候,buffer 是1234, 如果利用test3返回的指针对其进行修改值。再次调用时会覆盖这个数组的内容。如下所示
    char *s=test3();
    cout<<s<<endl;//输出1234
    s[4]='5';
    char *h=test3();
    cout<<h<<endl;//输出12345
    cout<<s<<endl;//输出12345

    char *buffer=(char *)malloc(10);
    test4(buffer);
    cout<<buffer<<endl;

    //还有一种使用全局变量的方法,这里省略了
}

猜你喜欢

转载自blog.csdn.net/jxhaha/article/details/70805876