使用strlen()时如何将一个char数组传递给另一个char数组?

时间:2018-07-29 22:01:09

标签: c++

#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;
}

error

如何解决此错误?

  

错误:我是未声明的标识符

array2[i]=NULL;

1 个答案:

答案 0 :(得分:0)

int ifor循环范围内声明,因此您不能在循环外部(之前或之后)使用它。您可以在循环上方声明它,以便在循环之后和内部使用它:

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;
}