c语言 - 为什么当我使用函数作为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参数,则会得到错误的答案。 你能解释一下为什么会这样吗?

"调试是学习的重要来源。" -可能是智者

笔记:

  1. 在函数FuncA()中,您将返回一个局部变量,一旦它超出函数范围,该变量将被销毁。因此,FuncA()将返回一个无效的指针,这将导致未定义的行为
  2. 返回堆分配的变量或具有static链接的变量
  3. FuncA()的返回值应该是const char *,而不仅仅是char *
  4. 函数FuncA()FuncB()都应通过static链接声明
  5. 在函数FuncB()变量ab都应属于const char *类型,因为稍后不会在代码中更改它们。
  6. 如果你的任何函数接受零参数,那么像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;
}

最新更新