嗨,我想将一个结构数组传递给一个方法,而不是打印它的值,但是当我尝试它只打印零时,请注意主要工作良好,问题出在 max 方法中:
#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)
}
但是当我尝试运行它时它崩溃了。
最佳答案
当前您正在将指针传递给结构体指针,但在函数 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
关于无法打印传递的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34034660/