2017-04-07 67 views
-5

我正試圖解決這個練習。簡單的二維

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

在你認爲你用一個二維數組的情況:你不知道。一個指針不是一個數組,指針數組也不是一個二維數組。 – Olaf

+0

Review for for(i = 0; i chux

+0

我不能無論如何讀它。修復縮進。 – ThingyWotsit

回答

-1

它不是正確的,因爲你聲明

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

,並呼籲

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 
} 
以最好的方式

你會得到錯誤的數據,acoording在內存中的一些數據; 其他方式你的程序將訪問衝突粉碎,嘗試使用其他程序

正確的方式採取memroy這將是

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;      
}