2017-04-07 69 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;      
}