Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sentinels in non-pointer arrays

Tags:

c

Let's say I have the following array:

int numbers[] = {-2,4,9,11};
int sum=sum_list(numbers);

If I were to pass pointers, I could add in a NULL at the end of the list to signal the size of it. However, in the above non-pointer list, is there a way to do that? If not, is the way around this just to explicitly pass the size of the array to the callee, for example:

int sum_list(int numbers[], size_z len);
like image 572
David542 Avatar asked Dec 18 '25 21:12

David542


1 Answers

When dealing with an array of non-pointer values such as this, you basically have two choices:

  1. Pass the length of the list to any function that also receives the list
  2. Designate some value that is outside the range of acceptable values to use as an end-of-list indicator

A third choice would be to implement a Pascal-type array where index 0 contains the length of the array.

like image 160
dbush Avatar answered Dec 20 '25 10:12

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!