花活儿:c/c++ 函数返回一个字符数组

你可能会很疑惑 为什么我要研究c/c++用函数返回一个数组

首先这个

其实c来返回一个数组等比较复杂的数据类型的变量是比较麻烦的。因为c系语言是强类型语言。而python是弱类型。比如python 直接定义 i = 1即可,c却要int i =1;python 的函数return 谁都可以

因为python对类型没有很强的约束。可是你 c就是写死了。

 

用c返回一个数组在嵌入式开发等环境中还经常会用到。比如串口写数据,写一大长串,就是字符,就是char数组,也就是char*

这些东西想好好写 那函数就得返回一些字符数组,甚至是结构体。。。

我以前没这么写过 我刚开始是类似这样写的:


复制代码
#include <iostream>
#include<typeinfo>
#include<stdio.h>
using namespace std;



 char *GetString(void)
{
    char str[] = "hello";
    return str;
}


int main()
{

    printf("%s\n",GetString());
    cout<<sizeof(GetString())<<endl;
    cout<<typeid( GetString() ).name()<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}
复制代码

 

 

 

结果:

 

 

 

 

 

 我靠 我hello呢???

我猜测是这样。因为我是局部变量定义的。这个函数运行完就释放内存了。所以hello本来就不应该有了。一个指针类型的局部变量,她返回的是局部变量的地址。可是局部变量用完就被释放了。

那怎么写。唉,首先,最简单的,用全局变量就行的啦。

 

复制代码
#include <iostream>
#include<typeinfo>
#include<stdio.h>
using namespace std;

char str[] = "hello";


 char *GetString(void)
{
    str[0] = 's';
    return str;
}


int main()
{

    printf("%s\n",GetString());
    cout<<sizeof(GetString())<<endl;
    cout<<typeid( GetString() ).name()<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}
复制代码

 

 

 

 

好。下面开始整活。

 

我用静态局部变量行不行?

复制代码
#include <iostream>
#include<typeinfo>
#include<stdio.h>
using namespace std;




 char *GetString(void)
{
    static char str[] = "hello";
    return str;
}


int main()
{

    printf("%s\n",GetString());
    cout<<sizeof(GetString())<<endl;
    cout<<typeid( GetString() ).name()<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}
复制代码

 

结果:

 

 行啊,这不就方便多了吗。静态变量他会一直存在的。这就是对代码掌握熟了的好处了。有些全局变量你写了还真的不好找。可是你用静态变量写了函数里,它好找,这个代码可读性一下子就上去了。

 

还有。如果说我们动态分配内存呢?内存那可是实打实的。不去free他就一直有

复制代码
#include <iostream>
#include<typeinfo>
#include<stdio.h>
#include<stdlib.h>
using namespace std;




 char *GetString(void)
{
    char *str = (char*)malloc(sizeof("hello")); 
    str = "hello";
    return str;
}


int main()
{

    printf("%s\n",GetString());
    cout<<sizeof(GetString())<<endl;
    cout<<typeid( GetString() ).name()<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}
复制代码

 

 

 

其实。最好用的是这种 就传参就行了

 

复制代码
#include <iostream>
#include<typeinfo>
#include<stdio.h>
#include<stdlib.h>
using namespace std;




 char *GetString(char *str)
{
    return str;
}


int main()
{
    char* str2 = GetString("hello");
    printf("%s\n",str2);
    cout<<sizeof(str2)<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}
复制代码

 

posted @   然终酒肆  阅读(1192)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示