L-40 MCS 260 Wed 21 Nov 2001

In this lecture we went deeper into the technical aspects of arrays. In C, the bracket notation is just a syntactical help. If you master the manipulation of arrays with pointer arithmetic, you have a better understanding of arrays. This understanding will help you when dealing with more advanced data structures in future courses.
/* L-40 MCS 260 Wed 21 Nov 2001 : dynamic memory allocation 

The program below reads in n floats, a scaling factor, and
returns the n floats multiplied with that scaling factor.    */

void read ( int n, float *f );
/* reads n numbers */

void write ( int n, float *f );
/* writes the vector to screen */

float* scale_v1 ( int n, float *f, float factor );
/* returns a scaled sequence of floats, multiplied by the factor,
   this is a messy pointer version */

void scale_v2 ( int n, float f[], float factor, float sf[] );
/* returns in sf a sequence of floats, multiplied by the factor,
   this is clean, but the caller must ensure memory for sf */

#include<stdio.h>

int main(void)
{
   float *data,*scaled, fac;
   int n;

   printf("Give number of floats : ");
   scanf("%d", &n);

   data = (float*) calloc(n, sizeof(float));

   printf("Give %d floats : ", n);
   read(n,data);

   printf("Your floats : ");
   write(n,data); printf("\n");

   printf("Give scaling factor : ");
   scanf("%f", &fac);

  /* remove the comments in the next statement to call pointer version */

  /* scaled = scale_v1(n,data,fac);  */

  /* please note that the bracket version requires memory allocation */

   scaled = (float*) calloc(n,sizeof(float));
   scale_v2(n,data,fac,scaled);

   printf("The scaled data : ");
   write(n,scaled); printf("\n");

   free(data);
   free(scaled);

   return 0;
}

void read ( int n, float *f )
{
   float *p;

   for (p = f; p < f+n; p++)
      scanf("%f", p);
}

void write ( int n, float *f )
{
   float *p;

   for (p = f; p < f+n; p++)
      printf(" %f", *p);
}

float* scale_v1 ( int n, float *f, float factor )
{
   float *result, *p_to_f, *p_to_result;

   result = (float*) calloc(n,sizeof(float));

   p_to_result = result;
   for (p_to_f = f; p_to_f < f+n; p_to_f++)
      *(p_to_result++) = *p_to_f * factor;

   return result;
}

void scale_v2 ( int n, float f[], float factor, float sf[] )
{
   int i;

   for (i = 0; i < n; i++)
      sf[i] = factor*f[i];
}