我正在编写以下代码:
#include<iostream>
#include<stdio.h>
using namespace std;
main() {
unsigned char a;
a=1;
printf("%d", a);
cout<<a;
}
Run Code Online (Sandbox Code Playgroud)
它打印1和一些垃圾.
为什么cout表现如此?
#include <stdio.h>
char* fun1()
{
char *s="hello";
return s;
}
char* fun2()
{
char s[6]="hello";
return s;
}
main()
{
char *str;
str = fun1();
printf("%s",str);//hello
str = fun2();
printf("%s",str);//garbage value
}
Run Code Online (Sandbox Code Playgroud)
代码的输出是 - hello和一些垃圾.我不明白虽然fun1和fun2中的两个变量都是各自函数的本地变量,为什么输出就是这样.两个函数调用都返回局部变量的地址,返回的地址应该包含垃圾值,这在fun1情况下不是真的它打印"你好".