小编Tob*_*obs的帖子

从函数返回char*和char []有什么区别?

为什么第一个函数返回字符串"Hello,World",但第二个函数不返回任何内容.我认为两个函数的返回值都是未定义的,因为它们返回的数据超出了范围.

#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;
}
Run Code Online (Sandbox Code Playgroud)

c string pointers

66
推荐指数
4
解决办法
4729
查看次数

标签 统计

c ×1

pointers ×1

string ×1