Matrix Initialization

问题描述 投票:0回答:1

I have the following code that deals with reading matrix which uses double pointers. I would like to understand why would author choose to use double pointers as follows:

int N=10;
int i,j;
open = (long double**)calloc(N+2, sizeof (long double*));
for(i=0;i<N+2;i++)
  open[i]=(long double*)calloc(N+2, sizeof (long double));

Usage

long double coord[500][2];
for(i=0;i<N+1;i++){
    fscanf(fin,"%s %s",column1,column2);
    coord[i][0]=atof(column1);
    coord[i][1]=atof(column2);
for(i=0;i<N;i++){
    for(j=0;j<N;j++)
        open[i][j]=sqrt(pow(coord[i][0]-coord[j][0],2.)+pow(coord[i][1]-coord[j][1],2.));

I failed to see how is the matrix initialized with double pointer while only a single array is declared open[i] instead of open[i][j]

c matrix double-pointer
1个回答
0
投票

Presumably the declaration is

long double **open;

The first malloc() allocates an array of pointers. Each pointer points to a row of the matrix.

The malloc() calls in the for loop allocate memory for each row of the matrix.

This is how you allocate a 2-dimensional matrix dynamically.

Since you're allocating a matrix of long double, you need to use that type in the sizeof calls.

© www.soinside.com 2019 - 2024. All rights reserved.