字符串和字符串函数用C [英] Strings and string functions in C
本文介绍了字符串和字符串函数用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了以下内容:
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
字符*的getString();字符*的getString(){
焦炭海峡[10];
得到(STR);
返回海峡;}诠释主(){ 字符* S;
S =的getString();
的strcpy(S,你好);
看跌期权(S);
返回0;
}
我知道 STR
的长度必须小于10少,但即使当我写只是正在打印什么也没有。据我看到它,它应该没问题。编译器说,与fgets是危险的,不应该使用
。
什么是被打印在屏幕上什么原因呢?
解决方案
字符海峡[10];
// ...
返回海峡;
这是<强>的错!的时,它们的范围退出局部变量是无效的;因此利用返回的数组是不确定的行为。你必须到malloc的字符串,返回它:
的strdup回报(STR);
I wrote the following:
#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;
}
I know that the length of str
must be less than 10, but even when I wrote just "Hi", nothing was being printed. as far as I see it, it should be Ok. the compiler says that fgets is dangerous and should not be used
.
What is the reason that nothing being printed on the screen?
解决方案
char str[10];
// ...
return str;
This is wrong!!! Local variables are invalidated when their scope exits; thus using returned array is undefined behavior. You have to malloc a string and return it:
return strdup(str);
这篇关于字符串和字符串函数用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文