首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在使用strlen()时,如何将字符数组传递给另一个字符数组?

在使用strlen()时,如何将字符数组传递给另一个字符数组?
EN

Stack Overflow用户
提问于 2018-07-30 06:01:09
回答 1查看 25关注 0票数 -3
代码语言:javascript
复制
#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;
}

如何修复此错误?

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

array2[i]=NULL;

EN

回答 1

Stack Overflow用户

发布于 2018-07-30 06:08:15

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

代码语言:javascript
复制
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;
}

下一个示例可能会帮助您理解作用域的概念:

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51584909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档