【问题标题】:Why the function fail to return pointer [duplicate]为什么函数无法返回指针[重复]
【发布时间】:2020-10-01 03:22:56
【问题描述】:
你好我想问一下为什么greet函数返回指针失败
#include <stdio.h>
#include <stdlib.h>
char *greet(){
char a[] = "hello world!"
return a;
}
int main(){
printf("%s",greet());
}
【问题讨论】:
标签:
c
pointers
scope
static
local-variables
【解决方案1】:
该函数返回一个指向本地数组a的第一个元素的指针,该元素具有自动存储持续时间。
退出函数后,指针变为无效,因为数组不再存在。
要么定义函数,比如制作具有静态存储持续时间的数组
char *greet( void ){
static char a[] = "hello world!"
return a;
}
或者使用指向字符串字面量的指针,该字面量又具有静态存储持续时间,例如
char *greet( void ){
char *a = "hello world!"
return a;
}
注意函数的参数列表中要包含void。