这里是简单的代码,只读两个矩阵一个是3 * 3维,另一个是3 * 1维。在打印第一个矩阵A [3] [3]时,矩阵的最后一个元素在void printarray(double **A, int n )
函数中打印为零。
在我的代码下面:
#include <stdio.h>
#include<malloc.h>
void printarray(double **A, int n );
void main(){
double **A;
int n = 3;
int row,col;
double *b;
A = (double **) malloc(n * sizeof(double**));
for (row = 1; row<= n; row++) {
A[row] = (double *) malloc(n * sizeof(double));
}
// Initialize each element.
for (row = 1; row<= n; row++) {
for (col = 1; col<= n; col++) {
printf("A[%d][%d]= %u \t",row,col,&A[row][col]);
scanf("%lf",&A[row][col]); // or whatever value you want
}
}
//print A
printf("\n...........array in main.................\n");
for (row = 1; row<= n; row++) {
for (col = 1; col<= n; col++) {
printf("A[%d][%d]=%u \t %lf",row,col,&A[row][col],A[row][col]);
printf("\n");
}
}
b = (double *) malloc(n * sizeof(double));
printf("\n enter the elemet of b \n"); // Initialize each element.
for (row = 1; row<= n; row++){
printf("address=%u \t",&b[row]);
printf("b[%d]=",row);
scanf("%lf",&b[row]);
printf("\n");
}
printarray((double **)A, n );
}// Print it
void printarray(double **A, int n ){
int i;
int j;
printf("\n.....print a.............\n");
for( j = 1; j <= n; j++ ){
for( i = 1; i <= n; i ++){
printf("A[%d][%d]= %u \t",j,i,&A[j][i]);
printf( "%lf ", A[j][i] );
}
printf( "\n" );
}
}
答案 0 :(得分:1)
问题之一来自数组的索引。数组索引从0
开始。
这意味着,为了遍历您的数组,您需要for
循环从0
开始,直到n-1
:
for (int row=0; row<n;++row) {/*...*/}