函數返回值為字符串的幾種寫法


#include <cstdio>
#include <cstring>
#include <iostream>

#include <string>
#include <Windows.h>
using namespace std;
void fun(char *s){//通過形參返回字符串
    strcpy(s, "hello");
}
char *fun2(char *s){//另一種寫法,
    strcpy(s, "hello");
    return s;//返回形參地址,方便程序調用
}


char *fun3(void){
    static char s[100];//不能使非靜態變量,否則子函數結束,局部變量被釋放,調用者得到一個無效的地址。
    strcat(s, "hello");
    return s;
}
char *fun4(void){
    char *s;
    s = (char *)malloc(100);
    strcpy(s, "hello");
    return s;//返回s值,該地址需要調用者去free釋放
}

//定義全局變量
char globle_buf[100];
void fun5(void){
    strcpy(globle_buf, "hello");
}
char *fun6(char *s){//另一種寫法
    strcpy(globle_buf, "hello");
    return globle_buf; //返回全局變量地址,方便程序調用
}
int main(){
    
    char *s2;
    fun3();
    s2 = fun3();
    cout << s2 << endl;
    fun3();
    cout << s2 << endl;
    system("pause");
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM