Visual Studio c ++显示第24行的"string"有一个数组元素,但top包含用户输入的所有文本.但是当我发送到PutString()时,它就消失了.为什么?
#include <stdio.h>
void PutString( const char* pChar ){
for( ; *pChar != 0; pChar++ )
{
putchar( *pChar );
}
}
char* GetString(){
char c[100];
int i = 0;
do
{
c[i] = getchar();
}while( c[i++] != '\n' );
c[i] = '\0';
// PutString( c );
return c;
}
void main(){
char* string = GetString();
PutString( string );
}
Run Code Online (Sandbox Code Playgroud)
因为c是一个局部变量GetString而你正在返回它的地址,之后它就会消失(移出范围).这是未定义的行为 - 你不允许使用超出范围的东西.事实上,如果你通过gcc它,它会非常明确地告诉你:
qq.cpp:9: warning: address of local variable ‘c’ returned
Run Code Online (Sandbox Code Playgroud)
如果你想从一个函数返回非简单的东西(比如数组而不是整数或浮点数,它们为你制作一个副本),你需要(例如)动态分配它,以便它能够在函数返回时存活.改变的事情:
char c[100];
Run Code Online (Sandbox Code Playgroud)
成:
char *c = malloc (100); // or equivalent 'new'.
Run Code Online (Sandbox Code Playgroud)
(当然记得最终释放/删除它).
即使您在返回时可能会在调试器中看到它GetString,但仍然无法按照标准进行保证.
无论如何,下一次堆栈操作(例如调用PutString)很可能会消除这些信息.
这是一个C++版本的new/delete方式:
#include <stdio.h>
void PutString (const char* pChar ){
for (; *pChar != 0; pChar++)
putchar( *pChar );
}
char* GetString (void) {
char *c = new char[100]; // memory behind c will survive ...
int i = 0;
do {
c[i] = getchar();
} while (c[i++] != '\n');
c[i] = '\0';
return c;
} // ... past here ...
int main (void) {
char* string = GetString();
PutString (string);
delete[] string; // ... until here.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我还应该提一下,在C(fgets或看到我的早期答案)和C++(例如字符串getline和char数组getline)中获得基于行的输入可能有更好的方法.