atari1356
11-11-2003, 06:23 PM
I'm learning C and am working through the book "Teach Yourself C Programming In 21 Days". I bought the book a long time ago, but it looks like it's online (http://lib.daemon.am/Books/C/) too (illegally?)... I'm having problems with exercise 9 and 10 of chapter 9 (http://lib.daemon.am/Books/C/ch09/ch09.htm#Heading20) :
9. Write a function named addarrays() that accepts two arrays that are the same size. The function should add each element in the arrays together and place the values in a third array.
10. ON YOUR OWN: Modify the function in exercise 9 to return a pointer to the array containing the totals. Place this function in a program that also displays the values in all three arrays.
Here's my program... I'm doing something wrong on line 14 (and maybe other places too), but don't know how to fix it... and for some reason they left out the answer from the back of the book. :confused:
#include <stdio.h>
#define ARRAYSIZE 5
int x[ARRAYSIZE] = { 1, 2, 3, 4, 5 };
int y[ARRAYSIZE] = { 10, 20, 30, 40, 50 };
int count;
int addarrays(int x[], int y[], int size);
main()
{
int *mypointer;
/* this is the line my compiler doesn't like */
mypointer = addarrays(x, y, ARRAYSIZE);
for(count = 0; count < ARRAYSIZE; count++)
{
printf("\n%d\t%d\t%d", x[count], y[count], *(mypointer + count));
}
}
int addarrays(int x[], int y[], int size)
{
int count, z[size];
int *ptr_to_z = z;
for( count = 0; count < size; count++)
{
z[count] = x[count] + y[count];
}
return *ptr_to_z;
}
9. Write a function named addarrays() that accepts two arrays that are the same size. The function should add each element in the arrays together and place the values in a third array.
10. ON YOUR OWN: Modify the function in exercise 9 to return a pointer to the array containing the totals. Place this function in a program that also displays the values in all three arrays.
Here's my program... I'm doing something wrong on line 14 (and maybe other places too), but don't know how to fix it... and for some reason they left out the answer from the back of the book. :confused:
#include <stdio.h>
#define ARRAYSIZE 5
int x[ARRAYSIZE] = { 1, 2, 3, 4, 5 };
int y[ARRAYSIZE] = { 10, 20, 30, 40, 50 };
int count;
int addarrays(int x[], int y[], int size);
main()
{
int *mypointer;
/* this is the line my compiler doesn't like */
mypointer = addarrays(x, y, ARRAYSIZE);
for(count = 0; count < ARRAYSIZE; count++)
{
printf("\n%d\t%d\t%d", x[count], y[count], *(mypointer + count));
}
}
int addarrays(int x[], int y[], int size)
{
int count, z[size];
int *ptr_to_z = z;
for( count = 0; count < size; count++)
{
z[count] = x[count] + y[count];
}
return *ptr_to_z;
}