C语言——数组

1.字符型数组与字符指针的赋值

   const char *pStr = "Hello!";
    char aStr[sizeof("Hello!")] = "Hello!";
    cout << aStr << "\n" << pStr << endl;
    cout << strlen(aStr) << "\n" << strlen(pStr) << endl;
    cout << sizeof(aStr) << "\n" << sizeof(pStr) << endl;

    // 输出:
    // Hello!
    // Hello!
    // 6
    // 6
    // 7
    // 4

    // pStr是一个指向字符串常量的指针(常量存储在数据区的常量段)
    // aStr是一个指向一个栈区字符串的指针
    // strlen计算字符串的长度(一直计算到'\0')
    // sizeof计算变量、数组的长度

2.多维数组与数组的指针

    int array[4][5][6] = {
        {{1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}},
        {{1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}},
        {{1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}},
        {{1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}}};

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 5; j++) {
            for (int k = 0; k < 6; k++) {
                cout << array[i][j][k];
            }
            cout << "\n";
        }
        cout << "number :" << i << endl;
    }

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 5; j++) {
            for (int k = 0; k < 6; k++) {
                cout << *(*(*(array + i) + j) + k);
            }
            cout << "\n";
        }
        cout << "number :" << i << endl;
    }

数组名指向数组的第一个元素,也是数组的指针

    cout << array << endl;
    cout << &array << endl;

3.指针数组在字符串上的使用

    const char *array[3] = {"hello", "coca", "cola"};
    cout << array[0] << endl;
    cout << array[1] << endl;
    cout << array[2] << endl;

 

posted on 2023-11-17 21:37  _燃灯续昼  阅读(8)  评论(0编辑  收藏  举报

导航