c - C 中的字符串和字符串函数

标签 c string strcpy

我写了以下内容:

#include <stdio.h>
#include <string.h>
char* getString();

char* getString(){
    char str[10];
    gets(str);
    return str;

}

int main() {

    char* s;
    s=getString();
    strcpy(s,"Hi");
    puts(s);
    return 0;
}

我知道 str 的长度必须小于 10,但即使我只写了“Hi”,也没有打印任何内容。据我所知,应该没问题。编译器说 fgets 很危险,不应该使用

屏幕上什么都不打印是什么原因?

最佳答案

char str[10];
// ...
return str;

这是错误的!!!局部变量在其作用域退出时失效;因此使用返回的数组是未定义的行为。你必须 malloc 一个字符串并返回它:

return strdup(str);

关于c - C 中的字符串和字符串函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11517298/

相关文章:

c - getenv ("cc") 返回 NULL ,为什么?

c - 发出取消引用指针

c++ - 如何在 C++ 中通过函数名 (std::string) 调用函数?

c++ - string::size_type 而不是 int

c - 在 C 中更新字符串

C - 将一个字符复制到另一个

c++ - Linux ioctl -> 如何判断当前 IP 是否由 dhcp 获取

c - 是否可以将 stdout 重定向到 C 中的两个位置?

regex - R在data.frame中获取双/三重姓氏的首字母

c - 使用 strcpy 的段错误