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
参数,则会得到错误的答案。 你能解释一下为什么会这样吗?
"调试是学习的重要来源。" -可能是智者
笔记:
- 在函数
FuncA()
中,您将返回一个局部变量,一旦它超出函数范围,该变量将被销毁。因此,FuncA()
将返回一个无效的指针,这将导致未定义的行为 - 返回堆分配的变量或具有
static
链接的变量 FuncA()
的返回值应该是const char *
,而不仅仅是char *
。- 函数
FuncA()
和FuncB()
都应通过static
链接声明 - 在函数
FuncB()
变量a
和b
都应属于const char *
类型,因为稍后不会在代码中更改它们。 - 如果你的任何函数接受零参数,那么像
type func(void) { }
最终代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char* FuncA(void)
{
static const char str[50] = "ex"; // static linkage
return str;
}
void FuncB(void)
{
const char* a = FuncA();
const char* b = FuncA();
int i = strcmp(FuncA(), FuncA()); // 0
int j = strcmp(a, b); // 0
printf("%dn%dn", i, j);
}
int main(void)
{
FuncB();
return EXIT_SUCCESS;
}