#include <stdio.h>
char *getString()
{
char str[]="textprint";
}
int main()
{
printf("%c",getString());
return 0;
}
在输出中接收此垃圾值的原因是什么?
答案 0 :(得分:3)
gcc -Wall
编译代码可以获得多个警告代码:
#include <stdio.h>
// version 2
// this is a change done after all other warnings were resolved,
// if you try it yourself, keep the version 1 (see below) to see the
// enlightening warning
char str[]="textprint";
// example for "localisation" strings
char strFr[] = "imprimertexte";
const char *getString(void) // better signature
// (with void as parameter list) for function, for good practice;
// the keyword "const" prevents changing the global string,
// which is a safety precaution
{
// version 1 char str[]="textprint";
// this version 1, after all the other warnings are resolved,
// gets the enlightening warning
// "function returns address of local variable",
// so this got moved somewhere else for version 2
// Returning a pointer to a global variable/text from a function
// is not obviously useful - at first glance.
// One reason could be the design to be able to return different
// pointers to different strings, depending on some condition.
// I can imagine for example localisation of the texts.
// That could look like
// if(localisation == English) {return str;}
// else {return strFr;}
return str; // to avoid warnings
// a) "unused variable"
// b) "control reaches end of non-void function"
}
int main(void) // better signature for main, good practice
{
printf("%c",*getString()); // change what to print, in order to avoid warning
// "format '%c' expects type 'int', but argument 2 has type 'char *' " ,
// by changing from "pointer to char" to
// "what a pointer to char points to", i.e. "char"
printf("\n"); // print a newline for better readable output
// Alternative, for printing the complete text:
printf("%s\n", getString());
// this attempts to change the global string
// with the "const" keyword at the function head this does not work
// it gets: "error: assignment of read-only location '*getString()'"
// *getString()='T';
return 0;
}
答案 1 :(得分:1)
您可能想看看这个:
#include <stdio.h>
char * getString(void)
{
const * str = "textprint test";
return str;
}
int main()
{
printf("%s\n", getString() );
return 0;
}
请参阅演示here
我在没有const关键字的情况下在codepad.org上运行了这个代码段,但根据这个article,可能有必要避免编译器发出警告。
代码创建一个字符串文字,存储在内存中的只读位置,指针保存其地址。当getString()执行时,它的返回值是指向该字符串文字的指针。
根据上述article:
“C和C ++标准说字符串文字有静态存储”
这表明OP的代码可以兑换,修改如下:
#include <stdio.h>
char * getString(void)
{
static char str[] = "textprint";
return str;
}
int main()
{
printf("\n%s",getString());
return 0;
}
请参阅演示here
在此示例中,创建的是一个数组,以便每个元素包含一个包含该字符串的字符。除了添加关键字“static”之外,该数组只存在于getString()的范围内,这极大地延长了该数组的生命周期。因此,当getString()在main()中执行时,返回值是指向内存中保持完整的数组的地址。
注意,getString()必须包含一个return语句,以便将funciton作为printf()的参数进行求值。此外,如果不指定关键字 static ,地址将指向损坏的内存,从而导致生成的垃圾数据。
答案 2 :(得分:-1)
您忘记添加退货声明。
return str;