2017-04-07 6 views
-5

私はこの課題を解決しようとしています。 単純に2次元

https://gyazo.com/043018a2e547b4bfb4ef9eb1adfd707a

は、しかし、私の現在のコードで、私は出力としてこれを取得しています。

https://gyazo.com/13ed434ec876e145931b45e6d12a02fc

現在、これは私が持っているコードです。

#include <stdio.h> 
#include <stdlib.h> 
#define r 3 
#define c 5 

int main(int argc, char *argv[]) 
{ 
int i, j; 
float *a[r], sum; 

freopen("testdata2", "r", stdin); 

for(i = 0; i < r; i++) 
{ 
    float *row = (float*)malloc(sizeof(float)*c); 
    for(i = 0; i < c; i++) 
{ 
    scanf("%f", &row[i]); 
} 
    a[i] = row; 
} 

printf("The average values for the three rows are: "); 
for(i = 0; i < r; i++) 
{ 
    sum = 0; 
    for(j = 0; j < c; j++) 
{ 
    sum += a[i][j]; 
} 
    printf("%.2f", sum/c); 
} 

printf("\nThe average values for the three columns are: "); 
for(i = 0; i < c; i++) 
{ 
    sum = 0; 
    for(j = 0; j < r; i++) 
{ 
    sum += a[i][j]; 
} 
    printf("%.2f", sum/r); 
} 
return 0; 
} 
+0

になり、他のプログラム

正しい方法で撮影したmemroyを使用しようと、アクセス違反により鎮圧されます:あなたはしないでください。ポインタは配列ではなく、2次元配列のポインタの配列でもありません。 – Olaf

+0

「for(i = 0; i chux

+0

私はできませんとにかくそれを読んでください。インデントを修正します。 – ThingyWotsit

答えて

-1

あなたは

float *a[r] /* r = 3 */ 
int i; 

を宣言し、メモリ内の一部のデータにacoording、間違ったデータを取得する最良の方法で

for(i = 0; i < r; i++) { 
    float *row = (float*)malloc(sizeof(float)*c); 

    for(i = 0; i < c; i++) { // just write for(int i =0; i < c ; i++) { 
    scanf("%f", &row[i]); // or use j here; 
    } 

    a[i] = row; // i = c /* 5 */ here 
       // a[4] and a[5] are not located 
} 

を呼び出し、その正しくない原因。 他の方法あなたのプログラムは、それはあなたが2次元配列を使うと思う場合

for(int i = 0; i < r; i++) { 
    float *row = (float*)malloc(sizeof(float)*c); 

    for(int j = 0; j < c; j++) { 
     scanf("%f", &row[j]); 
    } 

    a[i] = row;      
}