2015-12-02 37 views
0

嗨我想要傳遞一個結構數組,而不是打印它的值,但是當我嘗試它只打印零時,請注意主要工作得很好問題是在最大方法中:無法打印傳遞的結構

#include <stdio.h> 
#include <stdlib.h> 

struct rectangle { 
    float length; 
    float width; 
}; 

void max (struct rectangle * a, int size){ 
    printf("the test %d \n", (*a).width); 
    int i; 
    for(i=0; i<size; i++){ 
    printf("the test %d \n", a[i].width); 
    } 
}  


void main() 
{ 
    printf("enter the size of both arrays \n"); 
    int x ; 
    scanf("%d",&x); 

    struct rectangle* r ; 
    r = malloc(x*sizeof(struct rectangle)); 
    int j ; 
    for (j = 0 ; j < x ; j++){ 
    printf("enter rectangle length \n"); 
    scanf("%f",&r[j].length); 
    printf("enter rectangle width \n"); 
    scanf("%f",&r[j].width); 
    } 

    for (j = 0 ; j < x ; j++){ 
    printf(" %f\n",r[j].length); 
    printf(" %f\n",r[j].width); 
    } 
    max(r,x) 

} 

但是當我嘗試運行它崩潰。

+2

'a = a + i'會導致問題,因爲您會轉移太多。將其更改爲'a ++':) – tkellehe

+0

建議:如果您使用數組下標,而不是'** a',則會更容易理解和維護:例如'a [i] - > width'。 – kaylum

+0

完全取出'a = a + i;'並將'(** a)'改爲'(* a)[i]' –

回答

1

當前您正在將指針傳遞給結構指針,但在函數max中,您試圖以結構指針的形式訪問它。

使用max(r,x)而不是max(&r,x)

編輯:

此外,在max功能:

printf("the test %f \n", a[i].width); // use %f instead of %d 

或者,如果你真的希望他們打印爲%d,使用方式如下:

printf("the test %d \n", (int)a[i].width); // use %d, and typecast float to int 
+0

相同的問題 – user5277934

+0

我有一個測試3小時後,但我不知道如何解決這個問題, 請幫忙。 – user5277934

+0

@ user5277934仍然崩潰? – GNKeshava

0

裏面max您正在嘗試使用%d格式說明符打印float值。這將無法正常工作。 printf formaty說明符爲float值爲%f,而不是%d

裏面main你正確使用%f。你爲什麼突然在max切換到%d