我如何返回一个字符串以供使用?我不知道为什么这个功能不起作用。
#include <stdio.h>
char* test(){
char A[100];
scanf("%s", A);
printf("A = %s \n", A);
return(A);
}
main(){
char* B;
B = test();
printf("B = %s \n", B); // why this return (null)?
}
Run Code Online (Sandbox Code Playgroud)
这是未定义的行为。它可能会返回“正确”的值;它可能会做一些完全不同的事情,使程序崩溃,或者更糟。之所以是未定义行为,原因如下:
char* test(){
char A[100];
scanf("%s", A);
printf("A = %s \n", A);
return(A);
}
Run Code Online (Sandbox Code Playgroud)
char在这里,您在堆栈上声明了一个 100 的数组。稍后您将地址返回到该内存。但是,它在堆栈上,因此内存现在无效。然后将此无效内存指针分配给B:
char* B;
B = test();
Run Code Online (Sandbox Code Playgroud)
所以在这一行:
printf("B = %s \n", B); // why this return (null)?
Run Code Online (Sandbox Code Playgroud)
你有未定义的行为。
相反,试试这个:
char* test() {
char* A = malloc(100);
scanf("%s", A);
printf("A = %s \n", A);
return A;
}
Run Code Online (Sandbox Code Playgroud)
在此函数中,内存是在堆上分配的。这样,您返回的指针是有效的(另请注意,您不需要在Ain两边加上任何括号return A;)。不过,不要忘记再次释放内存。您可以通过在程序末尾调用以下命令来完成此操作:
free(B);
Run Code Online (Sandbox Code Playgroud)
请注意,对于您的代码,编译器可能会发出警告。它可能会这样说:
局部变量或临时变量的返回地址:A
这些警告可以帮助您发现潜在问题并调试代码。当程序无法运行时,请首先尝试解决所有警告。