无法打印传递的结构

标签 c struct

嗨,我想将一个结构数组传递给一个方法,而不是打印它的值,但是当我尝试它只打印零时,请注意主要工作良好,问题出在 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/

相关文章:

c++ - C stdio 字符编码

c - 如何通过子进程之间的共享内存共享信号量?

在 MinGW 下取消 pthread_cond_wait 中的线程会导致访问冲突

c - C 结构体中的结构体意味着什么?

c - 如何在指向整数的指针中输入数据?

python - 有没有人有一个很好的例子来说明如何使用 struct python 模块将 numpy 数组保存到文件中?

在共享内存中创建和访问结构

c - scanf 和 printf 不打印正确的值

c - 结构体入口声明了一个数组类型的字段,但编译器说它是一个指针

c# - 为什么我不能为 .NET 中的结构定义默认构造函数?