开发者

Filling 4 variable in a struct type and using malloc

I need to write a simple program that ask the user to insert 4 double开发者_StackOverflow type variable in a struct variable data.

   struct Data  
    {
      double a;
      double b;
      double c;
      double average;
    };
struct Data *ptr_name;
int i;

First, ask user the size:

 printf("Please enter the size:");
 scanf("%d", &size);

Then, use the malloc. (I dont know how to use it...)

something like this... ptr_name = ()malloc();

and then use the for loop to get the a, b, c from user.

for(i = 0; i < size; i++)
{
 //dont know how to put the staement..
}

finally, print everything out, including the average.

for(i = 0; i < size; i++)
    {
     //same as above...
    }

That is pretty much all, I am learning struct type and malloc now, can't understand by browsing web... help, thanks.


The call to malloc should be:

ptr_name = malloc (sizeof (struct Data) * size);

The following functions read/write instances of struct Data from/to the console:

static struct Data 
read_from_console ()
{
  struct Data d;

  d.a = 0.0f; d.b = 0.0f; d.c = 0.0f; d.average = 0.0f;
  printf ("Enter values separated by comma: (a, b, c): ");
  fflush (stdout);
  if (scanf ("%lf, %lf, %lf", &d.a, &d.b, &d.c) != 3)
    {
      printf ("Invalid input\n");
      exit (1);
    }
  else
    d.average = (double) ((d.a + d.b + d.c) / 3.0f);
  return d;
}

static void
print_to_console (struct Data* d)
{
  printf ("a=%f, b=%f, c=%f, average=%f\n", d->a, d->b, d->c, d->average);
  fflush (stdout);
}

You can call them from the loops inside the main function:

int
main ()
{
  struct Data *ptr_name;
  int count;
  int i;

  printf ("Please enter size: ");
  fflush (stdout);
  if (scanf ("%d", &count) != 1)
    {
      printf ("Invalid input\n");
      return 1;
    }
  ptr_name = malloc (sizeof (struct Data) * count);

  for (i = 0; i < count; ++i)
    ptr_name[i] = read_from_console ();

  for (i = 0; i < count; ++i)
    print_to_console (&ptr_name[i]);

  return 0;
}

A sample interaction:

> Please enter size: 2
> Enter values separated by comma: (a, b, c): 12.00, 12.45, 13.00
> Enter values separated by comma: (a, b, c): 5.4, 5.00, 5.1
a=12.000000, b=12.450000, c=13.000000, average=12.483333
a=5.400000, b=5.000000, c=5.100000, average=5.166667


Start with

ptr_name = malloc( size * sizeof( *ptr_name ) );

See wikipage on malloc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜