简体   繁体   中英

pointer to pointer as parameter of func

 void print_first_n_row(double **matrix, int n, int row) {
   int i,j;
   double x;
   for(i=0;i<n;i++){
     for(j=0;j<row;j++){
       x=*(*(matrix+i)+j);
       printf("%lf",x); 
    }
    printf("\n");
  } 
}

I am not getting output with this func. What can be reason?

In C, arrays are arranged in memory consecutively, row by row, referred to as row major for example, an array created like this:

int array[4][3] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};//4 rows of 3 columns

...is stored in memory as:

|1|2|3|4|5|6|7|8|9|10|11|12|
|row 1|row 2|row 3| row 4  |

So your function, as it is written , should be passing n as the number of rows to print in the second argument (as it does), but pass how many columns there are in the 3rd argument.

Change this:

void print_first_n_row(double **matrix, int n, int row)  

to this:

void print_first_n_row(double **matrix, int n, int col)    

I tested this change by creating [4][3] index accessible memory locations using allocated memory for: double **matrix; (4 pointers to double, each pointing to 3 double locations.) then populated each location with a series of numbers,and passed appropriate arguments:

int n = 4;
int col = 3;
void print_first_n_row(matrix, n, col);  

I saw this:

在此处输入图像描述

When passed:

int n = 2;
int col = 3;
void print_first_n_row(matrix, n, col);  

I saw this:
在此处输入图像描述

One other suggestion, as stated in comments:

This:

x = matrix[i][j];  

Is much more readable than:

x=*(*(matrix+i)+j);

"I am not getting output."

If you ain´t got output, either n or row (or even both) shall be 0 or smaller than 0 because if it would be different you shall get at least one output.

Check the values you pass as arguments to n and row in the calling function.

My personally assumption is that the newline form printf("\n"); is getting printed, but you didn´t noticed the output of the line feed.

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