#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"); }