【发布时间】:2020-09-24 18:24:14
【问题描述】:
为什么stringParser中t的值打印的是“Hello”,而main函数中没有?
#include <stdio.h>
char* stringParser(char st[]) {
char temp[100];
int i = 0;
while (st[i] != '\0') {
temp[i] = st[i];
i++;
}
temp[i] = '\0';
char* t = temp;
printf("%s", t);
return t; // Outputs: "Hello"
}
int main() {
char y[] = "Hello";
printf("\n%s", stringParser(y)); //Outputs: "╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠⌠²Ö"
return 0;
}
【问题讨论】:
-
@neostar 退出函数后返回的指针无效,因为自动存储时长函数的局部变量指向的数组不存在。
-
@Carcigenicate t 是一个指向字符串 temp 的指针,因此函数 stringParser() 应该返回该指针。 stringParser 的指针不应该保存字符串 temp 的值吗?
-
@neostar 一旦函数调用结束,函数内的所有局部变量都将被销毁,这里变量 temp 被销毁,因此您的函数返回一个指向 temp 地址但 temp 的值已被销毁的指针
-
可能与 Returning string from C function 重复?