0

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?

Community
  • 1
  • 1
Thatdude1
  • 905
  • 5
  • 18
  • 31
  • `n` is a size. It is telling you that it is passing in an array of `n` size. This is the most reliable method when passing an array to a function because `sizeof` won't return you the correct size. –  Mar 19 '12 at 14:07
  • The `int` parameters tell you the size/number of elements of the array. In C, arrays don't carry length information. – Daniel Fischer Mar 19 '12 at 14:09
  • 3
    This is so basic, covered in the first documentation you should be reading about C, I wonder if it belongs on stackoverflow at all. – blueshift Mar 19 '12 at 14:10
  • "Arrays" in C and C++ are not really arrays, but rather pointers to blocks of memory. The function cannot know the length of that block of memory (since it is just a bunch of numbers). Thus, you need the second parameter to tell the function how long that array actually is. – o_o Mar 19 '12 at 14:11
  • 7
    @ChongShaoWei: _Sigh._ [Arrays are _not_ pointers](http://stackoverflow.com/q/1641957/140719). – sbi Mar 19 '12 at 14:33
  • 1
    @ChongShaoWei, no you are wrong for arrays in general. Declarations of function parameter *look* as if they where declaring an array, but they don't. – Jens Gustedt Mar 19 '12 at 14:34
  • 2
    @0A0D: Why should this C question be part of the C++ FAQ? Feel free to explain this at the [C++ chatroom](http://chat.stackoverflow.com/rooms/10/loungec). Until then, I'll remove the FAQ tag. – sbi Mar 19 '12 at 14:35
  • @sbi: That's my fault.. thanks for clearing it. –  Mar 19 '12 at 16:32

3 Answers3

10

When passed to a function, an array decays into a pointer, which inherently stores no length. The second argument would store the number of elements in the array, so, it would look something like this:

int values[] = { 16, 13, 78, 14, 91 };
int count = sizeof(values) / sizeof(*values);

printf("sum of values: %i\n", sumarray(values, count));
printf("maximum position: %i\n", maxarraypos(values, count));
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • 1
    "When passed to a function, an array decays into a pointer, which inherently stores no length." You're obviously talking to a beginner; this probably zoomed right over their head. – jason Mar 19 '12 at 14:12
  • @Jason I suppose, but I'm not good at rephrasing for beginners, sorry . – Richard J. Ross III Mar 19 '12 at 14:22
  • 2
    @Jason: Maybe, but this is the only correct explanation I have seen so far. (`+1` from me.) I'd rather have beginners ask for clarifications of correct answers than walk away with simple, but incorrect ones. – sbi Mar 19 '12 at 14:45
2

for sumarray, im confused since an array stores something within a certain length, why would need the second parameter n?

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 n is for.

And also how would i test a function that consume's an array, i was thinking like sumarray([3], 3) .. is that right ?

No. You could say

int myArray[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

and then

int sum = sumarray(myArray, 10);

To solve all of these, you'll need loop (a for loop 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.

jason
  • 236,483
  • 35
  • 423
  • 525
  • This was downvoted? Please explain. – jason Mar 19 '12 at 14:26
  • 4
    I hadn't downvoted originally, but I will now, because of what you wrote is wrong: Arrays do come with their length attached to them: `sizeof(array)/sizeof(array[0])`. The trouble is that arrays so easily decay to pointers to their first element, at which point they aren't arrays anymore and the size information is lost. – sbi Mar 19 '12 at 14:43
  • 1
    Arrays do have their size encoded in the type. Pointers don't. If this is an attempt to not confuse beginners with details then I don't think that pretending that arrays are really involved with `sumarray` when they aren't at all is going to achieve that eventually. – Luc Danton Mar 19 '12 at 14:43
  • Alright i got sumarray to work. For maxarray when it say's to return the position, do i return an address ? – Thatdude1 Mar 19 '12 at 14:47
  • its wrong? i used a for loop and came up with this http://ideone.com/jkxlo ? o_o – Thatdude1 Mar 19 '12 at 15:05
  • 1
    @sbi: You can not use the method that you are proposing for array parameters passed to methods. This is a fundamental fact, and it's the reason every correctly written C program that passes arrays around also passes around their length. The array has decayed to a pointer, and the trick you propose does not work. I have *clarified* my answer, but there was nothing *wrong* about it in the sense that I correctly explained why he has to pass the length as a parameter to the method. I originally said "Arrays don't come with their lengths attached to them" meaning "Arrays as parameters don't...." – jason Mar 19 '12 at 15:36
  • @sbi: So read my answer again. Read the first threee sentences of my original answer. "You need the second parameter to tell you how long the array is. Arrays 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." I intended this to apply to arrays as parameters, but nonetheless I have elaborated to make this abundantly clear. – jason Mar 19 '12 at 15:42
  • 1
    @Beginnernato: No, you're fine. "For maxarray when it say's to return the position, do i return an address ?" Return the index of the maximum position. – jason Mar 19 '12 at 15:44
  • @sbi: No sbi, it wasn't wrong. It was open to misinterpretation from what I intended. I have clarified. – jason Mar 19 '12 at 15:45
  • @Jason: I will withdraw my downvote after this edit, but I won't upvote, because it's still not really correct: You cannot pass arrays to functions in C. – sbi Mar 19 '12 at 15:59
  • @sbi: Well, you're technically correct (the best kind of correct!) but you're also being pedantic. Yes, an array as a parameter immediately decays to a pointer, but the languages gives us the convenience of pretending that functions can receive arrays as parameters. – jason Mar 19 '12 at 16:13
  • 2
    @Jason: I know all this, and I'd wholeheartedly have upvoted any answer that would explain it in one piece and in as much detail as your comments now do. – sbi Mar 19 '12 at 16:34
  • @Jason Alrite im not on lexlt ... im confused say `a[] = {1 2 4}` and `b[] = {3 2 1 4}` how exactly would i check if `a` is less than `b` ? – Thatdude1 Mar 19 '12 at 19:25
  • It's like how you check if one word is less than another: word `a1a2a3...an` is less than `b1b2b3...bm` if and only if the first `aj` different than `bj` comes before `aj` or there is no such index and `n < m`. Similarly, compare the elements of the array one by one until you find the first index `j` where the arrays differ. If `a[j] < b[j]` then return `true`, otherwise return `false`; however, if there is no such index, then return `true` if `n < m`, otherwise return `false`. – jason Mar 19 '12 at 19:53
  • so if n < m its automatically true, but if n = m i need to check if every index and make sure 'a[j] < b[j]' ? – Thatdude1 Mar 19 '12 at 22:37
  • No. If `n < m` it is not automatically true. Note that 'baboon' comes after `alligator` in the dictionary, but `baboon` is shorter than `alligator`. – jason Mar 20 '12 at 03:01
1

im confused since an array stores something within a certain length, why would need the second parameter n?

Because you do not know the certain length. If you do not want to change the code when you change the length of the initial array, you need to pass around n because c language generally does not provide that information.

perreal
  • 94,503
  • 21
  • 155
  • 181
  • It does for array, but you cannot pass arrays to functions in C. – sbi Mar 19 '12 at 14:46
  • @sbi, there are also dynamic arrays – perreal Mar 19 '12 at 14:48
  • so if we say C stores size of arrays, it would be misleading – perreal Mar 19 '12 at 14:52
  • Actually, now that I think of it, are there dynamically allocated arrays in C at all? There are such beasts in C++, when you `delete[]` a dynamically created array in C++, the runtime system "knows" the array's size and invokes the destructor for all elements. But in C, all you can do dynamically is allocate a blob of memory, and then treat it as if it was some data type. Even if you treat it as if it is an array, to the runtime system it's still just a blob of memory. – sbi Mar 19 '12 at 14:58
  • @sbi, I understand your point but those blobs are generally referred to as arrays. For example `a` in `f(int *a, int n)` is called an array regardless of initialization semantics. Perhaps you are more accurate with regards to the meaning of the term. – perreal Mar 19 '12 at 15:03
  • 1
    Yes, it's generally said wrong. But that's where the confusion of newbies comes from, which is why, when not discussing with seasoned C programmers, but explaining to newbies, I'd insist on using the correct term. From most of the answers here newbies learn it wrong (the accepted answer says "Arrays in C don't come with their length attached to them.") and later will have to unlearn in order to make progress. – sbi Mar 19 '12 at 15:08