简体   繁体   中英

i want to know the purpose of the following c++ code

i understand the code creates a pointer variable as a 2d array. but i feel like instead of being used to store address of the another variable(2d array) the pointer variable is stored with the actual numbers so as to get away with the shortcomings of using just an array. am i right or wrong? help me improve my understanding of pointers.

double** assign_initial_guess(
    int nx,
    int ny,
    double top,
    double left,
    double right,
    double bottom,
    double interior)
{
    //n --> number of nodes in one direction
    //top,left,right,bottom,interior --> values need to assigned at respective nodes
    double** u=0;
    int ind=0;
    u=new double*[nx];

    for(int i=0;i<nx;i++)
    {
        u[ind]=new double[ny];
        for(int j=0;j<ny;j++)
        {
            u[i][j]=interior;
            if(i==0)
                { u[i][j]=top;} // top boundary

            if(j==0 && i>0 && i<(nx-1))
                { u[i][j]=left;} // left boundary

            if(j==(ny-1) && i>0 && i<(nx-1))
                { u[i][j]=right;} // right boundary

            if(i==(nx-1))
                { u[i][j]=bottom;} // bottom boundary
        }
        ind+=1;
    }
    return u;
}

I'm not sure if I understand what you really want to know, but:

Each variable (doesn't matter of what type), has it's own (sometimes shared with others, but lets skip that for a moment) place in your PC's memory. Pointers store information about the address of the memory in which a particular variable is at. The new operator in your code is used to assign some memory for a variable. The code your provided doest the following:

u=new double*[nx];

Allocates the memory needed to store nx pointers (so nx*sizeof(double*) ) and gets the address of the allocated memory. The address is stored in the pointer u .

u[ind]=new double[ny];

Allocates the memoy needed to store ny doubles (so ny*sizeof(double) ), and get the address of the allocated memory. The address is stored in the pointer u[ind] .

指针是对其他变量的引用,并且实际上不包含任何值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM