0

I have a function that prints out 11 points of a quadratic function ax^2 + bx + c with a, b, c as input. The function works fine except I need to use structures, not just variables x and y. How can I get my function to return a structure value and store it in a structure array then print out the structure array?

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;
}
3
  • Do you want (a) the main routine to create an array of structures, the findpoint routine to return one structure per call, and the main routine to store that structure in its array, (b) the main routine to create an array of structures and the findpoint routine to directly store values in one element of that structure per call, (c) the main routine to create an array of structures and the findpoint routine to store values in all of those structures in one call, (d) the findpoint routine to create an array of structures and return it, filled in, or (e) something else? Commented Nov 7, 2020 at 11:31
  • I'm trying to do the first option (a) where main stores the the structure and prints it Commented Nov 7, 2020 at 19:35
  • Okay, then the existing answer shows one way to do that. Commented Nov 7, 2020 at 19:39

1 Answer 1

0

You can create an alias for your struct with 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);
  }
    
}
Sign up to request clarification or add additional context in comments.

1 Comment

@DavidCullen Return a pointer to a local variable and return a struct are different things

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.