#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char array1[20]="hello world";
char array2[20];
for(int i=0;i<strlen(array1);i++)
array2[i]=array1[i];
array2[i]=NULL;
cout<<array2<<endl;
return 0;
}
如何解决此错误?
错误:我是未声明的标识符
在array2[i]=NULL;
答案 0 :(得分:0)
int i
在for
循环范围内声明,因此您不能在循环外部(之前或之后)使用它。您可以在循环上方声明它,以便在循环之后和内部使用它:
int main() {
char array1[20] = "hello world";
char array2[20];
int i;
for(i = 0; i < strlen(array1); i++)
array2[i] = array1[i];
array2[i] = NULL;
std::cout << array2 << std::endl;
return 0;
}
下一个示例可以帮助您理解范围的构想:
using namespace std;
int main() { // Main Scope
cout << j << endl; // Error - j is not declared yet
cout << i << endl; // Error - i is not declared yet
int i = 3; // i is now belong to the main scope.
{ // First Inner Scope
int j = 4; // j is now belong to the first inner scope.
{ // Second Inner Scope
string str = "aaa"; // str is now belong to the second inner scope.
cout << j << endl; // Work
cout << i << endl; // Work
cout << str << endl; // Work
}
cout << j << endl; // Work
cout << i << endl; // Work
cout << str << endl; // Error - str is not belong to this scope
}
cout << i << endl; // Work
cout << j << endl; // Error - j is not belong to this scope
cout << str << endl; // Error - str is not belong to this scope
return 0;
}