C++ two-dimensional array declaration and initialization example

C++ two-dimensional array declaration and initialization example

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
    int **a = new int *[10];
    char **c = new char *[10];
    string *str = new string[10];
    char temp[20] = "偶稀饭你!";
    //两层循环,int数组和char数组一并赋值了
    for (int i = 0; i < 10; i++)
    {
    
    
        a[i] = new int[10];
        c[i] = new char[20];
        for (int j = 0; j < 10; j++)
        {
    
    
            a[i][j] = 520;
        }
        memcpy(c[i], temp, sizeof(temp));
        c[i][sizeof(temp) + 1] = '\0';
    }

    //string数组赋值
    for (int j = 0; j < 10; j++)
    {
    
    
        str[j] = "稀饭你";
    }

    //输出
    for (int k = 0; k < 10; k++)
    {
    
    
        cout << *a[k] << endl
             << c[k] << endl
             << str[k] << endl
             << endl;
    }
    return 0;
}

Assign a two-dimensional array to a two-dimensional pointer

#include <iostream>
int main(int argc, char const* argv[])
{
    
    
    char test[10][10] = {
    
     {
    
    "一天"}, {
    
    "一夜"} };
    char* testp [10];
    for (int i = 0; i < 10; i++) {
    
    
        testp[i] = test[i];
    }
    char** temp = testp;
    std::cout << temp[0]
        << "\t"
        << temp[1]
        << std::endl;
        
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44575789/article/details/106627360