当我使用函数作为 strcmp 的参数时,为什么会得到不正确的值?
char *FuncA()
{
char str[50] = "ex";
return str;
}
void FuncB()
{
char *a = FuncA();
char *b = FuncA();
int i = strcmp(FuncA(), FuncA()); // 1
int j = strcmp(a, b); // 0
}
您好,我对 strcmp
现在的工作原理有点困惑。 FuncA()
只是一个返回字符串"ex"
的函数。 一旦保存 FuncA()
返回值并使用 strcmp
,您将得到正确的答案,但如果您使用 FuncA()
作为马上使用strcmp
参数,你会得到错误的答案。 你能解释一下这是为什么吗?
char *FuncA()
{
char str[50] = "ex";
return str;
}
void FuncB()
{
char *a = FuncA();
char *b = FuncA();
int i = strcmp(FuncA(), FuncA()); // 1
int j = strcmp(a, b); // 0
}
Hello, I'm a little confused about how strcmp
works now.FuncA()
is simply a function that returns the string "ex"
.
Once you save the FuncA()
return value and use strcmp
, you will get the correct answer, but if you use FuncA()
as a parameter of strcmp
right away, you will get the wrong answer.
Can you explain why this is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“调试是一个很好的学习来源。” - 可能是一个明智的人
注意:
funca()
中,您正在返回一个本地变量,该变量将一旦从功能范围中删除,该变量将被销毁。因此,funca()
将返回无效的指针 不确定的行为static 链接
funca()
的返回值应为const char *
,而不仅仅是char *
。funca()
和funcb()
应用static
linkagefuncb()
中 声明变量a
和b
均应为const char *
,因为您以后在代码中不更改它们。键入func(void){}
最终代码:
"Debugging is a great source of learning." -Probably a wise man
Notes:
FuncA()
you are returning a local variable which will be destroyed once it gets out of the function scope. Hence,FuncA()
will return an invalid pointer which will cause undefined behaviourstatic
linkageFuncA()
should beconst char *
, instead of justchar *
.FuncA()
andFuncB()
should be declared withstatic
linkageFuncB()
both the variablea
andb
should be of typeconst char *
as you aren't changing them later in your code.type func(void) { }
Final Code: