c语言 函数 返回 字符串_如何从C函数返回字符串-程序员宅基地

技术标签: python  java  c语言  字符串  指针  

c语言 函数 返回 字符串

In one of my C programs, I had the task to return a string from a function:

在我的一个C程序中,我的任务是从一个函数返回一个字符串:

xxxxx myName() {
  return "Flavio";
}

The tricky thing is defining the return value type.

棘手的事情是定义返回值类型。

Strings in C are arrays of char elements, so we can’t really return a string - we must return a pointer to the first element of the string.

C语言中的字符串char元素的数组,因此我们不能真正返回字符串-我们必须返回一个指向字符串第一个元素的指针。

This is why we need to use const char*:

这就是为什么我们需要使用const char*

const char* myName() {
  return "Flavio";
}

Here’s an example working program:

这是一个示例工作程序:

#include <stdio.h>

const char* myName() {
  return "Flavio";
}

int main(void) {
  printf("%s", myName());
}

If you prefer to assign the result to a variable, you can invoke the function like this:

如果您希望将结果分配给变量,则可以调用以下函数:

const char* name = myName();

We can write the pointer operator * also in this ways:

我们也可以这样编写指针运算符*

const char * myName()
const char *myName()

All forms are perfectly valid.

所有表格均完全有效。

Note the use of const, because from the function I’m returning a string literal, a string defined in double quotes, which is a constant.

注意const的用法,因为我从函数中返回一个字符串常量 ,即用双引号定义的字符串,它是一个常量。

Note that you can’t modify a string literal in C.

请注意,您无法在C中修改字符串文字。

Another thing to keep in mind is that you can’t return a string defined as a local variable from a C function, because the variable will be automatically destroyed (released) when the function finished execution, and as such it will not be available, if you for example try do do:

要记住的另一件事是,您不能从C函数返回定义为局部变量的字符串,因为该变量将在函数执行完毕后自动销毁(释放),因此它将不可用,例如,如果您尝试做:

#include <stdio.h>

const char* myName() {
  char name[6] = "Flavio";
  return name;
}

int main(void) {
  printf("%s", myName());
}

you’ll have a warning, and some jibberish, like this:

您会收到警告和一些胡言乱语,如下所示:

hello.c:5:10: warning: address of stack memory
      associated with local variable 'name'
      returned [-Wreturn-stack-address]
  return name;
         ^~~~
1 warning generated.
B��Z> K���⏎

Notice the B��Z> K���⏎ line at the end, which indicates that the memory that was first taken by the string now has been cleared and there’s other random data in that memory. So we don’t get the original string back.

请注意最后的B Z> K ⏎行,这表明该字符串最初占用的内存已被清除,并且该内存中还有其他随机数据。 因此,我们不会取回原始字符串。

Changing myName() to

myName()更改为

const char* myName() {
  char *name = "Flavio";
  return name;
}

makes the program work fine.

使程序正常运行。

The reason is that variables are allocated on the stack, by default. But declaring a pointer, the value the pointers points to is allocated on the heap, and the heap is not cleared when the function ends.

原因是默认情况下变量是在堆栈上分配的。 但是声明一个指针后,指针指向的值将分配到堆上 ,并且在函数结束时不会清除堆。

翻译自: https://flaviocopes.com/c-return-string/

c语言 函数 返回 字符串

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/cuk0051/article/details/108319671

智能推荐

Promise与async和await的总结_promiseresult await-程序员宅基地

文章浏览阅读132次。Promise语法上 Promise 是一个构造函数Promise 构造函数:Promise (excutor)()Promise.prototype.thenPromise.prototype.catchPromise.allSettled:不管数组中的 Promise 是否成功或失败 都会执行完全部成功就调用resolve,失败调用reject //实例化 Promise 对象 const p = new Promise(function(resolve, reject)_promiseresult await

each循环-程序员宅基地

文章浏览阅读1.7k次。一、each的两种写法(1)遍历元素节点 $(node).each(function(index,element) { console.log(index); console.log(element); }) (2)遍历数组,数据格式 $.e...

java截取字符串_java根据下标获取字符-程序员宅基地

文章浏览阅读1.5k次。1.根据下标截取:String str = str.substring(开始的下标,截取的长度)2.根据字符截取://截取_之前字符串:String str = str.substring(0, str.indexOf("_"));------------------------------------------------------------------//截取_之后字符串:String str = str.substring(0, str.indexOf("_"));String_java根据下标获取字符

iscsi配置_在linux操作系统上配置iscsi的服务器targetcli不小心退出了-程序员宅基地

文章浏览阅读1.7k次。一、环境配置(安装)服务器端:yum install targetcli #管理程序systemctl start target #打开服务客户端:yum install iscsi-initiator-utils #iscsi应用程序通常这个都安装过了。二、targetcli的配置服务器端: 首先要有一块需要共享的硬盘分区,这是我要共享的..._在linux操作系统上配置iscsi的服务器targetcli不小心退出了

QTreeWidget详细使用介绍_qtreewidget用法-程序员宅基地

文章浏览阅读1.1w次,点赞10次,收藏87次。QTreeWidget继承自QTreeView,是通过树形结构来展示数据结构的控件。1.QTreeWidget和QTreeView的区别QTreeView一般和相应的QXXModel合用,形成Model/View结构.QTreeView是一个视图类,你需要手动给其指定模型类,才能够显示数据。QTreeWidget继承自QTreeView,是封闭了默认Model的QTreeView,应用了模型/视图的编程方法,将数据和显示分开了。就灵活性来讲,QTreeView要灵活些。QTreewidg._qtreewidget用法

Android CameraX和SurfaceView的基本使用_camerax surfaceview-程序员宅基地

文章浏览阅读1.9k次。Jetpack CameraX 库 的 PreviewView 可以帮助您解决这一问题。通过在各种 Android 设备上提供开发者友好、一致且稳定的 API,使得展示相机的预览变得不再困难。_camerax surfaceview

随便推点

docker如何查看容器ip_docker 容器 ip-程序员宅基地

文章浏览阅读5.6k次。docker exec -it xxx sh 进入容器终端cat /etc/hosts 显示ip所在的配置文件_docker 容器 ip

Qt之按钮(QAbstractButton)-程序员宅基地

文章浏览阅读1.5k次。简述QAbstractButton是按钮控件的抽象基类,提供了按钮所共有的功能。这个类实现了一个抽象的按钮。对这个按钮进行子类化可以处理用户行为,以及指定按钮如何绘制。QAbstractButton提供了点击和勾选按钮。QRadioButton和QCheckBox类只提供了勾选按钮,QPushButton和QToolButton提供了点击按钮,如果需要的话,它们还可以提供切换行为。任何按钮...

Springboot集成Lettuce完成Redis cluster集群的key过期监控-程序员宅基地

文章浏览阅读2.7k次。经过几天各种方案的对比及实验,终于完成了Springboot集成Lettuce完成Redis cluster集群的key过期监控的代码,主要参考了如下的文章及代码:https://my.oschina.net/u/4134799/blog/3116221/printhttps://github.com/xfearless1201/api/blob/master/src/mai...

Vuex介绍&同步取值&异步问题_vuex同步异步获取数据的区别-程序员宅基地

文章浏览阅读5.5k次,点赞3次,收藏9次。前言:我们在之前就有了子类与父类之间的传参,又有利用总线进行传参,但两者都有一定的弊端。如:总线定义组件太多容易混淆等;所以接下来我们会利用VueX进行参数传。目录一:VueX简介一:VueX简介官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库), 让其在各个页面上实现数据的共享包括状态,并且可操作 Vuex分成五个部分: 1.State:单一状态树 2.Getters:状态获取 3..._vuex同步异步获取数据的区别

servlet返回数据的方法_servlet 返回值-程序员宅基地

文章浏览阅读2.6w次,点赞2次,收藏17次。servlet返回数据的方法方法1. RequestDispatcher.forward()界面跳转 HttpSession session =request.getSession(); Object obj = session.getAttribute (LoginConstants.LOGIN_USER); if (null !=..._servlet 返回值

golang string 去最后一个字符_golang 取字符串最后一个元素-程序员宅基地

文章浏览阅读1.8w次。package mainimport ( "fmt" "strings")func main() { fmt.Println("Hello, 世界") var s string s = "333," strings.TrimRight(s, ",") fmt.Println(s) s = strings.TrimRight(s, ",") fmt.Println(s)..._golang 取字符串最后一个元素

推荐文章

热门文章

相关标签