c语言 函数 返回 字符串
In one of my C programs, I had the task to return a string from a function:
在我的一个C程序中,我的任务是从一个函数返回一个字符串:
xxxxx myName() {
return "Flavio";
}
The tricky thing is defining the return value type.
棘手的事情是定义返回值类型。
Strings in C are arrays of char
elements, so we can’t really return a string - we must return a pointer to the first element of the string.
C语言中的字符串是char
元素的数组,因此我们不能真正返回字符串-我们必须返回一个指向字符串第一个元素的指针。
This is why we need to use const char*
:
这就是为什么我们需要使用const char*
:
const char* myName() {
return "Flavio";
}
Here’s an example working program:
这是一个示例工作程序:
#include <stdio.h>
const char* myName() {
return "Flavio";
}
int main(void) {
printf("%s", myName());
}
If you prefer to assign the result to a variable, you can invoke the function like this:
如果您希望将结果分配给变量,则可以调用以下函数:
const char* name = myName();
We can write the pointer operator *
also in this ways:
我们也可以这样编写指针运算符*
:
const char * myName()
const char *myName()
All forms are perfectly valid.
所有表格均完全有效。
Note the use of const
, because from the function I’m returning a string literal, a string defined in double quotes, which is a constant.
注意const
的用法,因为我从函数中返回一个字符串常量 ,即用双引号定义的字符串,它是一个常量。
Note that you can’t modify a string literal in C.
请注意,您无法在C中修改字符串文字。
Another thing to keep in mind is that you can’t return a string defined as a local variable from a C function, because the variable will be automatically destroyed (released) when the function finished execution, and as such it will not be available, if you for example try do do:
要记住的另一件事是,您不能从C函数返回定义为局部变量的字符串,因为该变量将在函数执行完毕后自动销毁(释放),因此它将不可用,例如,如果您尝试做:
#include <stdio.h>
const char* myName() {
char name[6] = "Flavio";
return name;
}
int main(void) {
printf("%s", myName());
}
you’ll have a warning, and some jibberish, like this:
您会收到警告和一些胡言乱语,如下所示:
hello.c:5:10: warning: address of stack memory
associated with local variable 'name'
returned [-Wreturn-stack-address]
return name;
^~~~
1 warning generated.
B��Z> K���⏎
Notice the B��Z> K���⏎
line at the end, which indicates that the memory that was first taken by the string now has been cleared and there’s other random data in that memory. So we don’t get the original string back.
请注意最后的B Z> K ⏎
行,这表明该字符串最初占用的内存已被清除,并且该内存中还有其他随机数据。 因此,我们不会取回原始字符串。
Changing myName()
to
将myName()
更改为
const char* myName() {
char *name = "Flavio";
return name;
}
makes the program work fine.
使程序正常运行。
The reason is that variables are allocated on the stack, by default. But declaring a pointer, the value the pointers points to is allocated on the heap, and the heap is not cleared when the function ends.
原因是默认情况下变量是在堆栈上分配的。 但是声明一个指针后,指针指向的值将分配到堆上 ,并且在函数结束时不会清除堆。
c语言 函数 返回 字符串