In my effort to learn C on my own, I am using Stephen Prata's book; it has some great assignments.
This is the assignment:
Write a program that initializes an array-of-double and then copies the contents of the array into two other arrays. (All three arrays should be declared in the main program.) To make the first copy, use a function with array notation. To make the second copy, use a function with pointer notation and pointer incrementing. Have each function take as arguments the name of the target array and the number of elements to be copied. That is, the function calls would look like this, given the following declarations:
double source[5] = {1.1, 2.2, 3.3., 4.4, 5.5};
double target1[5];
double target2[5];
copy_arr(source, target1, 5);
copy_ptr(source, target1, 5);
and here is my code solution:
Code:
#include <stdio.h>
#define ITEMS 5
double source[ITEMS] = {1.1, 2.2, 3.3, 4.4, 5.5};
double target1[ITEMS] = {0.0};
double target2[ITEMS] = {0,0};
void copy_arr(double [], double [], int);
void copy_ptr(double *, double *, int);
void print_results(void);
int counter;
int main(void)
{
printf("BEFORE calling functions\n");
print_results();
copy_arr(source, target1, ITEMS);
copy_ptr(source, target2, ITEMS);
printf("AFTER calling functions\n");
print_results();
return 0;
}
void copy_arr(double source[], double target[], int items)
{
for (counter = 0; counter < items; counter++) target[counter] = source[counter];
return;
}
void copy_ptr(double * source, double * target, int items)
{
for (counter = 0; counter < items; counter++)
{
*target = *source;
source++; target++;
}
return;
}
void print_results(void)
{
printf("*----------------------------*\n");
printf("SOURCE : ");
for (counter = 0; counter < ITEMS; counter++) printf("%1.1lf ", source[counter]); printf("\n");
printf("TARGET1 : ");
for (counter = 0; counter < ITEMS; counter++) printf("%1.1lf ", target1[counter]); printf("\n");
printf("TARGET2 : ");
for (counter = 0; counter < ITEMS; counter++) printf("%1.1lf ", target2[counter]); printf("\n");
printf("*----------------------------*\n");
return;
}
how does it look? it works fine -- here are the results I get:
Code:
BEFORE calling functions
*----------------------------*
SOURCE : 1.1 2.2 3.3 4.4 5.5
TARGET1 : 0.0 0.0 0.0 0.0 0.0
TARGET2 : 0.0 0.0 0.0 0.0 0.0
*----------------------------*
AFTER calling functions
*----------------------------*
SOURCE : 1.1 2.2 3.3 4.4 5.5
TARGET1 : 1.1 2.2 3.3 4.4 5.5
TARGET2 : 1.1 2.2 3.3 4.4 5.5
*----------------------------*
Press any key to continue . . .
Is my code OK in your opinion? in terms of style etc.?