-1

I understand that passing an array to a function in C passes a pointer to the first element. Lets say I have a function, and receive an array of integers. Is there a way to get the number of elements in the array, without passing the size as an argument, or using a sentinel value? I want something portable, similar to looping through a string and counting until getting to '\0'. Thanks!

I tried looping through and using '\0' but the result differs alot. Any tips?

0xCESR
  • 1
  • 1
    Pass the length of the array as another argument to the function. – Shawn Aug 14 '23 at 05:49
  • 2
    The array is passed as a pointer, and in doing so any information about the size of the array is lost. If you do not have a sentinel value marking the last element in the array and the array size is unknown or otherwise cannot be inferred from its contents, then you must supply the size. If you want something portable (and familiar), then pass the size. This is an extremely common pattern in C, for good reason. – paddy Aug 14 '23 at 05:52
  • "without passing the size as an argument, or using a sentinel value" \0 is a sentinel value. Check out the linked duplicate and if that doesn't answer the question then please clarify what you want and add a code example of what you tried. – Lundin Aug 14 '23 at 06:23
  • For strings you have the null-terminator character `'\0'` (assuming it's correctly terminated). For other arrays there's no such thing unless you explicitly added it. If you have problems with strings, then please try to create a [mre], then [edit] your question to show it together with a detailed description of the code, what it's supposed to do, and what happens when you run it. – Some programmer dude Aug 14 '23 at 06:30
  • Also please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], and [ask]. Then also read [how to write the "perfect" question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/), especially its [checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Aug 14 '23 at 06:32
  • You can't as they decay to pointer, you need to pass another variable for its length – Darth-CodeX Aug 14 '23 at 06:36

0 Answers0