Originally Posted by
rstanley
Instead of:
Code:
void arrayFunc(int myArray, etc..) //other variables may be pointers? i.e. int *sum or something along those lines
You need to pass the array name as a pointer to an int, and the dimension of the array. You also should not use "Magic Numbers" in your code.
The function should be defined as:
Code:
void arrayFunc(int *arrayPtr, int dim)
{
// ...
}
And call the function as:
Code:
#define DIM 5
// ...
arrayFunc(myArray, DIM);
The name of the array is the address (Pointer) of the first element of the array.
I leave the rest of the code to you. You have everything you need.
If your instructor / book / YouTube video where you learned C did not provide you with this information, then you need a new teaching source!
Thanks for this.
I came up with two versions, messing around with stuff.
Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5;
void arrayFunc(int arr[], int *sum, int i);
int main()
{
int myArray[SIZE];
int sum = 0;
int i;
for (i = 0; i < SIZE; i++)
{
printf("Please enter #%d: ", i+1);
scanf("%d'", &myArray[i]);
}
for (i = 0; i < SIZE; i++)
arrayFunc(myArray, &sum, i);
printf("%d", sum);
return 0;
}
void arrayFunc(int arr[], int *sum, int i)
{
*sum += arr[i];
}
And keeping in mind your example of intializing as a pointer in the function..
Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5;
void arrayFunc(int *arr, int *sum, int i);
int main()
{
int myArray[SIZE];
int sum = 0;
int i;
for (i = 0; i < SIZE; i++)
{
printf("Please enter #%d: ", i+1);
scanf("%d'", &myArray[i]);
}
for (i = 0; i < SIZE; i++)
arrayFunc(myArray, &sum, i);
printf("%d", sum);
return 0;
}
void arrayFunc(int *arr, int *sum, int i)
{
*sum += *(arr+i);
}
I haven't tried putting the dimensions of the array in the actual function but I will try that too