从函数返回char *和char []有什么区别? [英] What is the difference between returning a char* and a char[] from a function?

查看:118
本文介绍了从函数返回char *和char []有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第一个函数返回字符串"Hello,World",而第二个函数什么都不返回.我认为这两个函数的返回值都是不确定的,因为它们返回的数据超出范围.

Why does the first function return the string "Hello, World" but the second function returns nothing. I thought the return value of both of the functions would be undefined since they are returning data that is out of scope.

#include <stdio.h>
// This successfully returns "Hello, World"
char* function1()
{
    char* string = "Hello, World!";
    return string;
}
// This returns nothing
char* function2()
{
    char string[] = "Hello, World!";
    return string; 
}

int main()
{
    char* foo1 = function1();
    printf("%s\n", foo1); // Prints "Hello, World"
    printf("------------\n");
    char* foo2 = function2(); // Prints nothing
    printf("%s\n", foo2);
    return 0;
}

推荐答案

第二个函数不返回任何内容

the second function returns nothing

第二个函数中的string数组:

char string[] = "Hello, World!";

具有自动存储期限.从函数返回控制流后,它不存在.

has automatic storage duration. It does not exist after the control flow has returned from the function.

第一个函数中的string:

char* string = "Hello, World!";

指向具有静态存储持续时间的文字字符串.这意味着,从函数返回后,字符串仍然存在.从函数返回的是指向此文字字符串的指针.

points to a literal string, which has static storage duration. That implies that, the string still exists after returning back from the function. What you are returning from the function is a pointer to this literal string.

这篇关于从函数返回char *和char []有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆