C 此字符数组是否返回未定义的行为?
一个同学有这样一个功能:C 此字符数组是否返回未定义的行为?,c,undefined-behavior,C,Undefined Behavior,一个同学有这样一个功能: char* Func( int a ) { if( a == 0 ) return "yes"; else return "no"; } 我知道return a local char*是未定义的,但当我问他时,他说因为“yes”和“no”没有声明为变量,所以这不是未定义的行为 谁是对的?为什么?这里没有本地数组,显示的代码定义良好 该函数只返回一个类型为char的指针,这里实际上只是返回一个字符串,而不是对任何数组的引用
char* Func( int a )
{
if( a == 0 )
return "yes";
else
return "no";
}
我知道return a local char*是未定义的,但当我问他时,他说因为“yes”和“no”没有声明为变量,所以这不是未定义的行为
谁是对的?为什么?这里没有本地数组,显示的代码定义良好 该函数只返回一个类型为
char
的指针,这里实际上只是返回一个字符串,而不是对任何数组的引用
char *func(int a)
{
char b[10];
char *p = b;
if( a == 0)
return p;
}
这里您有一个错误,我想编译器会报告/警告它,因为您正在返回对本地数组的引用。数组
b
的生存期正好在func()
内,当您退出函数时,数组就不再有效了。您的代码运行正常,我尝试了以下内容:
#include <stdio.h>
#include <string.h>
char* Func(int a)
{
if (a == 0)
return "yes";
else
return "no";
}
int main(int argc, char *argv[])
{
char a[5] = { 0, };
strcpy(a, Func(0));
printf("returned %s",a);
return 0;
}
给出输出:
返回no
它应该是const char*
,但除此之外,它是可以接受的。他是对的;返回的地址仍然有效,代码格式正确。您在删除答案中回答了我想知道的问题。(因为“yes”是字符串文字,所以它有一个静态变量生存期。谢谢。请注意,“working fine”是未定义行为的成员。@tia,谢谢,这里我试图传达的是,行为依赖于它在调用函数(main()
)中的用法,而不是函数Func())
本身,如他的问题中所述。
#include <stdio.h>
#include <string.h>
char* Func(int a)
{
if (a == 0)
return "yes";
else
return "no";
}
int main(int argc, char *argv[])
{
char a[5] = { 0, };
strcpy(a, Func(1));
printf("returned %s",a);
return 0;
}