美文网首页
字符串(一)

字符串(一)

作者: iMikasa_ | 来源:发表于2021-11-17 09:28 被阅读0次

字符串作为函数的返回值

函数中声明的字符数组是局部变量

#include <stdio.h>
char *test_string();
int main(int argc, char const *argv[])
{
    printf("%s\n",test_string());
    
    return 0;
}
char * test_string(){
    char str[] = "abcdefg";
    return str;
}

我们编译程序发现警告,如下图


image.png

警告告诉我们函数返回的是局部变量的地址,我们为什么不能返回局部变量的地址呢?因为当函数执行完毕后,函数内声明的变量都会被销毁,所以不能返回局部变量;那我们如何返回字符串呢?我们可以返回通过指针声明的字符串,他就是字符串常量的地址,而字符串常量是常量,直到程序结束才会被销毁,说以可以正常的作为函数的返回值,如下代码

#include <stdio.h>
char *test_string();
int main(int argc, char const *argv[])
{
    printf("%s\n",test_string());
    
    return 0;
}
char * test_string(){
    char *str = "abcdefg";
    return str;
}

程序可以正常编译运行.....

其他返回字符串的方式

使用static

用static修饰字符数组,函数返回静态局部变量,如下

#include <stdio.h>
#include <string.h>
#define LEN 40
char *test_string(char *s);
int main(int argc, char const *argv[])
{
    printf("%s\n",test_string("abcd"));
    printf("%s\n",test_string("hello"));
    return 0;
}
char * test_string(char *s){
    static char str[LEN];
    strcpy(str,s);
    return str;
}
使用全局变量

这个很好理解。全局变量在程序真个生命周期中都是有效的,所以使用全局变量也可以解决类似问题。
但是这种方案就会让这个封装的方法耦合了,因为它依赖了全局变量。

#include <stdio.h>
#include <string.h>
#define LEN 40
char *test_string(char *s);
char *all_str;
int main(int argc, char const *argv[])
{
    printf("%s\n","hello");
    return 0;
}
char * test_string(char *s){
    strcpy(all_str,s);
    return all_str;
}
使用malloc

使用malloc函数动态分配,但是一定要注意在主调函数中将其释放,应为malloc动态分配的内存位于堆区,而堆区的内存是要程序员自己释放的。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 40
char *test_string(char *s);
int main(int argc, char const *argv[])
{
    char *str = test_string("hello world");
    printf("%s\n",str);
    free(str);
    return 0;
}
char * test_string(char *s){
    char * str ;
    str = (char *)malloc(strlen(s)*sizeof(char));
    strcpy(str,s);
    return str;
}

相关文章

  • Javascript知识点整合

    字符串 单行字符串: ‘字符串’或“字符串” 多行字符串: `多行字符串` 字符串操作: 字符串连接‘+’号 长度...

  • C++基础字符串

    字符串的构造 字符串特性描述 字符操作 字符串赋值 字符串连接 字符串比较 字符串查找 字符串替换 字符串删除 字...

  • iOS 字符串常用处理方法

    一、字符串截取 二、判断字符串是否包含某个字符串 三、字符串转数组&&数组转字符串

  • Swift 基本语法(字符串, 数组, 字典)

    前言 接上篇, 这篇聊一下 Swift中的 字符串, 数组, 字典 一 字符串 字符串的长度字符串的拼接字符串格式...

  • iOS中的NSString与NSMutableString

    字符串的创建 字符串读写 字符串的比较 字符串的搜索 字符串截取 字符串替换 字符串与路径 字符串转换 NSMut...

  • iOS NSString用法总结

    字符串属性 字符串截取 字符串比较 字符串搜索 字符串拼接 字符串基本类型转换 字符串分行,分段 字符串列举(按条...

  • js第八章

    正则和字符串 [if !supportLists]一、[endif]字符串 字符串的特点:同数组一样,字符串也有下...

  • php 字符串常见方法汇总

    字符串拼接 字符串检索 字符串截取 字符串替换 字符串大小写转化 字符串转数组 字符串格式化

  • 正则中的字符串

    一、字符串 2.字符串中的API 所有字符串中的API都无权修改原字符串,必须返回新字符串

  • iOS开发这些最基础的东西你确定你都知道吗

    一、字符串 1、不可变字符串的创建(NSSString) 2、字符串的比较 3、字符串的处理 4、可变字符串的创建...

网友评论

      本文标题:字符串(一)

      本文链接:https://www.haomeiwen.com/subject/nuqktrtx.html