Possible Duplicate:
when do we need to pass the size of array as a parameter
So I just started working with arrays, I have 3 functions i need to create to get me to learn.
int sumarray(int a[], int n);
// a is an array of n elements
// sumarray must return the sum of the elements
// you may assume the result is in the range
// [-2^-31, 2^31-1]
int maxarraypos(int a[], int n);
// a is an array of n elements
// maxarraypos must return the position of
// the first occurrence of the maximum
// value in a
// if there is no such value, must return 0
bool lexlt(int a[], int n, int b[], int m);
// lexicographic "less than" between an array
// a of length n and an array b of length m
// returns true if a comes before b in
// lexicographic order; false otherwise
How exactly would I create these functions?
For sumarray, I’m confused since an array stores something within a certain length. Why would need the second parameter n?
And also how would I test a function that consumes an array? I was thinking like sumarray([3], 3) .. is that right?
You need the second parameter to tell you how long the array is. Arrays as parameters to methods in C don’t come with their length attached to them. So if you have a method that takes an array as a parameter, it can’t know the length unless you also pass that to the method. That’s what
nis for.No. You could say
and then
To solve all of these, you’ll need loop (a
forloop is best, I’m sure your lecturer provided examples on how to loop over the elements of an array). Beyond that, I’m not doing your homework. Ask specific, pointed questions, and I’d be happy to consider answering them though.