首页 > 解决方案 > 将函数的返回值存储为 C 中的结构体数组

问题描述

我有一个函数可以打印出二次函数 ax^2 + bx + c 的 11 个点,输入为 a、b、c。该函数工作正常,除了我需要使用结构,而不仅仅是变量 x 和 y。如何让我的函数返回结构值并将其存储在结构数组中,然后打印出结构数组?

struct point {
    int x;
    int y;
};
struct point *findpoint(int a, int b, int c){
  int i, x, y;
  x = -5;
  for  (i = 0; i < 11; i++)
  {
    y = (a * (x * x)+ (b * x) + c);
    printf("The points are {%d, %d}\n", x, y);
    x++;   
  } 
}

struct point arr_point[11];

int main(int argc, char *argv[]){

struct point *ptr;
  printf("Enter coefficients a, b, c:");
  int a, b, c;
  int i;
  for (i = 0; i < argc; i++){
    scanf("%d %d %d", &a, &b, &c);
  }
  printf("%d %d %d\n", a, b, c);

  findpoint(a, b, c);
  return 0;
}

标签: cstructure

解决方案


您可以使用以下命令为您的结构创建别名typedef

typedef struct {
  int x;
  int y;
} Foo_t;

Foo_t returnStruct() {
    Foo_t foo = {1,2};
    return foo;
}

int main() {
  const uint8_t SIZE_ARRAY = 2;
  Foo_t arrayFoo[SIZE_ARRAY];

  arrayFoo[0] = returnStruct();
  arrayFoo[1] = returnStruct();
  for(uint8_t i=0;i<SIZE_ARRAY;i++) {
    printf("Index %d: x=%d y=%d \n", i, arrayFoo[i].x, arrayFoo[i].y);
  }
    
}

推荐阅读