我知道以下代码将创建一个字符数组并保留在内存中,直到程序结束:
char* str = "this is a string";
Run Code Online (Sandbox Code Playgroud)
至于这个语句,创建一个本地字符数组,当str超出范围时将被释放:
char str[] = "this is a string";
Run Code Online (Sandbox Code Playgroud)
我很好奇的是,当我这样写时会发生什么:
std::string str = "this is a string";
Run Code Online (Sandbox Code Playgroud)
str应该在它自己的内存(本地)中创建一个字符串的副本,但字符串文字本身呢?它是否具有程序的生命周期,或者当str超出范围时是否会被释放?
我一直以为“'\ n'in buffer”问题仅在我们读取字符时发生,但是,我偶然发现了以下代码:
int main(int argc, char** argv){
int height = 0, width = 0;
while(height < 1 || height > 10|| width < 1 || width > 15){
printf("Please insert the height(1~10) and width(1~15) of the parallelogram (integers): ");
if(scanf("%d %d", &height, &width) != 2){
height = width = 0;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如上所述,我只用scanf读取整数,但是当我输入无效的东西时,这段代码仍然陷入无限循环。如果清除缓冲区,它是固定的。
所以我的问题是,这是“'\ n'缓冲区”问题吗?还是仅在特殊用途下发生?如果仅在特殊用途下发生,我是否需要遵循一些一般准则?