花活儿: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("%sn",GetString());
    cout<<sizeof(GetString())<<endl;
    cout<<typeid( GetString() ).name()<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}

结果:

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

我靠 我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("%sn",GetString());
    cout<<sizeof(GetString())<<endl;
    cout<<typeid( GetString() ).name()<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}

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

好。下面开始整活。

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

#include <iostream>
#include<typeinfo>
#include<stdio.h>
using namespace std;




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


int main()
{

    printf("%sn",GetString());
    cout<<sizeof(GetString())<<endl;
    cout<<typeid( GetString() ).name()<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}

结果:

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

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

还有。如果说我们动态分配内存呢?内存那可是实打实的。不去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("%sn",GetString());
    cout<<sizeof(GetString())<<endl;
    cout<<typeid( GetString() ).name()<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}

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

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

#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("%sn",str2);
    cout<<sizeof(str2)<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}

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

原文链接: https://www.cnblogs.com/ranzhong/p/16192100.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/188803

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午2:28
下一篇 2023年2月12日 下午2:29

相关推荐